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 fact that len is a function means that classes cannot override this behaviour to avoid the check. As such, len(obj) gives a level of safety that obj. len() cannot.
Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.
The len() function returns the number of items in an object. When the object is a string, the len() function returns the number of characters in the string.
LEN returns the number of characters in a text string. LENB returns the number of bytes used to represent the characters in a text string.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With