This question already has an answer here:
- Understanding Python's slice notation 31 answers
a='0123456789' >>> a '0123456789' >>> a[1:-6:1] # working as expected '123' >>> a[2:-1:-1] # i was expecting '210' as answer based on start index=2 end index=0 ''
Please help in understanding how the second slice operator returned nothing
Negative indices for
stop are always converted by implicitly subtracting from
a[2:-1:-1] translates to
a[2:9:-1], which reads in English as "start at index 2, and go backwards by one until you're at or below index 9".
Since you start at index 2, you're already at or below 9, and the slice ends immediately.
If you want to slice from index to back to the beginning of the string, either omit the end index (which for negative slice means continue until "beginning of string"):
or provide it explicitly as
None, which is what omitting
stop ends up using implicitly: