Reverse string Python slice notation

扶醉桌前 提交于 2019-12-04 13:07:08

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!