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