In looking at some python strings and functions, I discovered this strange quirk of python:
s = "hello"
print s[::-1]
which then prints: olleh
However, print s[len(s)-1:-1:-1]
doesn't work. My understanding is that it should iterate from the last element s[len(s)-1]
to the first element s[0]
. However, it just prints an empty string ''
, which I believe is because in strings of some given length (say, 5), s[4] == s[-1]
. But, I don't understand why python decides to use -1
instead of 4
, which is the actual len(s)
.
Furthermore, s[len(s):0:-1] + s[0]
works. Why is len(s)
a valid index? Does python just convert len(s)
to 0 arbitrarily?
P.S. This is in Python 2.7.8, I'm not sure if it also works in 3.x.x
EDIT: Confirmed to be the same in Python 3
The slice notation is this:
s[start:stop:step]
specifically, stop
being up to but not including it. Translate this to what you're asking:
s[len(s)-1:-1:-1]
This is, based on the length of 5 for 'hello'
s[4:-1:-1]
or
s[4:4:-1]
which is an empty, or zero-length string.
I have given a much more in-depth exposition of the slice notation here: Explain Python's slice notation