What does extended slice syntax actually do for negative steps? [duplicate]

廉价感情. 提交于 2019-12-02 20:40:01

[-1:0:-1] means: start from the index len(string)-1 and move up to 0(not included) and take a step of -1(reverse).

So, the following indexes are fetched:

le-1, le-1-1, le-1-1-1  .... 1  # le is len(string)

example:

In [24]: strs = 'foobar'

In [25]: le = len(strs)

In [26]: strs[-1:0:-1]  # the first -1 is equivalent to len(strs)-1

Out[26]: 'raboo'

In [27]: strs[le-1:0:-1]   
Out[27]: 'raboo'

The Python documentation (here's the technical one; the explanation for range() is a bit easier to understand) is more correct than the simplified "every kth element" explanation. The slicing parameters are aptly named

slice[start:stop:step]

so the slice starts at the location defined by start, stops before the location stop is reached, and moves from one position to the next by step items.

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