Slice From Length to Beginning Index

Viewed 207

When slicing a string, I know that the notation is [start:stop:counter]. If that's the case though, if I have string = "hello", why does string[5:0:-1] return olleinstead of olleh? string[::-1] returns olleh for me so that is fine but I am confused on why the first syntax does not work

4 Answers

If we look at each term this creates in turn:

string[5] doesn't exist, so adds nothing
string[4] is "o"
string[3] is "l"
string[2] is "l"
string[1] is "e"

string[0] isn't called as Python ranges don't do the last element.

string[5:0:-1] here, ending index 0 is excluded, which is char h. In order to include fist char as well string[5::-1]

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array

Remember that the slicing for strings is from:up to (but not including):counter. Therefore, when you pass the -1 as the counter, this would essentially say, from the last character up to the first one, but not including it. Therefore: olle.

See that if you remove the 0, you also get the full string:

string[5::-1]

Returns:

olleh

As you can see,index 5 is out of range:

string = "hello"
#         01234
print(string[5:0:-1])

But that's okay, python will handle it by ignoring it.

Like:

print(string[100:0:-1])

Output:

olle

You know that in slices like string[0, 3], it will return 'hel' (the index 3 is not included), so same goes for backward slicing, the stop index is not included.

Your stop index is 0, which is the 'h', and so, the output doesn't include the 'h'.


If what you want is to reverse the string, you can:

print(string[::-1])

Output:

olleh
Related