简体   繁体   中英

Why does slicing in python stop at -1?

"abcde"[0:5:1] gives abcde. So I expected "abcde"[4:-1:-1] to return edcba but it gives nothing. Is there no way to get same result as "abcde"[4::-1] while explicitly giving middle parameter?

0 | 1 | 2 | 3 | 4

a | b | c | d | e

=============

[4:-1:-1]

 4  -> e

-1 -> e

-1 -> step back

=============

=> nothing between index 4 -> -1 with a step back

-1 in slicing in Python means: the 4rth (last before last). 4:-1 means then 4:4 -> empty string.

"abcde"[4::-1] # this gives "edcba"
"abcde"[4:-(len("abcde")+1):-1] # this too

You are slicing from the last index (4) to index 4 which results in an empty string. In other words, Python is doing the following:

"abcde"[4:4:-1]
# which is equal to
"abcde"[4:4]
# and evaluates to
""

If you slice from the last index (4) to the first index (0) with a stride of -1 you can reverse it. Thus the following code would work:

"abcde"[-1:0:-1]

Which in actual practice can be abbreviated to:

"abcde"[::-1]

If you need to use a number for the stop position, for example, you are using a variable to represent the stop index, then you can use the negative value equal to -len(obj) - 1 where obj is the object you want to reverse as the position before the first character:

>>> 'abcde'[4:-6:-1]
'edcba'

or,

>>> 'abcde'[-1:-6:-1]
'edcba'

Python list syntax is:

list[start:stop:step]

In the first example: start=0, stop=5, step=1. This is equivalent to the C style for loop:

for (i=0; i<5; i++)

In your second example, start=4, stop=-1=4, step = -1. This is equivalent to the C style for loop:

for (i=4; i>4; i--)

Since the start and stop conditions are the same, your result is empty.

Since -1 is a negative number, which as a start/stop is a special case in python list slicing that means "len(list)-1", you can't actually do the operation you want:

for (i=4; i>-1; i--)

So instead your best bet is "abcde"[::-1] which will correctly infer the end, and the start, from the direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM