Slice operator with end index 0 [duplicate]

  • A+
Category:Languages

This question already has an answer here:

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 start and stop are always converted by implicitly subtracting from len(sequence). So a[2:-1:-1] translates to a[2:len(a)-1:-1], or 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"):

a[2::-1] 

or provide it explicitly as None, which is what omitting stop ends up using implicitly:

a[2:None:-1] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: