Reverse string Python slice notation

2020-07-26 14:26发布

问题:

string = "HELLO"
print string[::-1] #as expected
print string[0:6:-1] #empty string why ?

I was amazed to see how easy it is to reverse a string in python but then I struck upon this and got lost. Can someone please explain why the second reverse does not works ?

回答1:

The reason the second string is empty is because you are telling the compiler to begin at 0, end at 6 and step -1 characters each time.

Since the compiler will never get to a number bigger than six by repeatedly adding -1 to 0 (it goes 0, -1, -2, -3, ...) the compiler is programmed to return an empty string.

Try string[6::-1], this will work because repeatedly adding -1 to 6 will get to -1 (past the end of the string).

Note: this is answer is mainly a compilation of @dmcdougall, @Ben_Love and @Sundeep's comments with a bit more explanation



回答2:

Slice notation is written as follows:

list_name[start_index: end_index: step_value]

The list indexes in python are not like the numbers present on number line. List indexes does not go to -1st after 0th index when step_value is -1.

Hence below results are produced

>>>> print string[0:6:-1]

>>>>

And

>>>> print string[0::-1]

>>>> H

So when the start_index is 0, it cant go in a cyclic order to traverse the indexes to -1, -2, -3, -4, -5, -6 for step_value is -1.

Similarly

>>>> print string[-1:-6:-1]

>>>> OLLEH

and

>>>> print string[-1::-1]

>>>> OLLEH

also

thus when the start_index is -1 it goes in a cyclic order to traverse the indexes to -1, -2, -3, -4, -5, -6 to give output OLLEH.

Its pretty straight forward to understand when start_index is 6 and step_value is -1

>>>> print string[6::-1]

>>>> OLLEH