Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when use negative number to slice a string in Python, 0 is disabled?

let's say I have a string:

>>>a = 'akwkwas'
>>>
>>>a[-3:]
'was'
>>>a[-3:None]
'was'
>>>a[-3:0]
''

why can't I use 0 as the end of the slice?

this is from docs:

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

The first row of numbers gives the position of the indices 0...6 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.

so when we use negative indices in loop , we should check the end's value, beacuse the end 0 in negative indices does not exist, such as when we split a string to a money-like string:

>>>a = '12349878334'
>>>print(','.join([a[-i-3:-i if i else None] for i in range(0, len(a), 3)][::-1])) 
>>>12,349,878,334
like image 817
Sinux Avatar asked Jul 31 '15 07:07

Sinux


People also ask

What happens when you use negative numbers in slicing notation in Python?

Negative Slicing in Python The slicing ends at the last item, which is at the index -1. Also, the step size can be a negative value. By doing this, the direction of slicing is reversed. This means the slicing starts from the sequence[stop + 1] and stops at the sequence[start] value.

What happens when you use negative numbers in slicing notation?

Using a negative number as an index in the slice method is called Negative slicing in Python. It returns the nth element from the right-hand side of the list (as opposed to the usual left-hand side).

How do you use negative slice in Python?

If an index number in a slice is out of bounds, it is ignored and the slice uses the start or end of the string. Negative Index As an alternative, Python supports using negative numbers to index into a string: -1 means the last char, -2 is the next to last, and so on.

How do you convert a negative number to a string in Python?

A function negative is defined to check if the number is negative. The str() function converts the number to a string data type. The if statement checks if the first character of the string is equal to the hyphen '-'. If the condition is True, the number is a negative number.


2 Answers

0 is the start of the sequence. Always, unambiguously. Changing its meaning to sometimes be the end would lead to a lot of confusion, especially when using variables for those two values.

Using negative indices is also not a different mode; negative indices are converted to positive indices relative to the length. Changing what element 0 refers to because the other slice input (start or stop) was a negative number makes no sense.

Because 0 always means the first element of the sequence, and there is no spelling for a negative zero, you cannot use 0 to mean the end of the sequence.

You can use None as the stop element to mean this instead, if you need to parameterise your indices:

start = -3
stop = None
result = a[start:stop]

You can also create a slice() object; the same rules apply for how indices are interpreted:

indices = slice(-3, None)
result = a[indices]

In fact, the interpreter translates the slice notation into a slice() object, which is then passed to the object to distinguish from straight-up indexing with a single integer; the a[start:stop] notation translates to type(a).__getitem__(a, slice(start, stop)) whereas a[42] becomes type(a).__getitem__(a, 42).

So by using a slice() object you can record either slicing or single-element indexing with a single variable.

like image 116
Martijn Pieters Avatar answered Oct 24 '22 10:10

Martijn Pieters


It is boring to use negative slice in a loop if there is some chance to slice to 'negative zero', because [:-0] is not interpreted as expected.

But there is a simple way to solve the problem, just convert negative index to positive index by adding the length of the container.

E.g. Negative Slice Loop:

a = np.arange(10)
for i in range(5):
    print(a[5-i:-i])

Answer:

[]
[4 5 6 7 8]
[3 4 5 6 7]
[2 3 4 5 6]
[1 2 3 4 5]

Convert to positive by adding the lenght:

for i in range(5):
    print(a[5-i:len(a)-i])

Get the right answer:

[5 6 7 8 9]
[4 5 6 7 8]
[3 4 5 6 7]
[2 3 4 5 6]
[1 2 3 4 5]
like image 43
吕廷博 Avatar answered Oct 24 '22 10:10

吕廷博