understanding negative slice step value [duplicate]

喜欢而已 提交于 2020-12-26 03:15:30

问题


I am having a problem in understanding what happens when i put negative value to step in case of slicing.

I know [::-1] reverses a string. i want to know what value it assign to start and stop to get a reverse.

i thought it would be 0 to end to string. and tried

f="foobar"

f[0:5:-1]---> it gives me no output. why?

and i have read start should not pass stop. is that true in case of negative step value also?

can anyone help me to clear my doubt.


回答1:


The reason why f[0:5:-1] does not generate any output is because you are starting at 0, and trying to count backwards to 5. This is impossible, so Python returns an empty string.

Instead, you want f[5:0:-1], which returns the string "raboo".

Notice that the string does not contain the f character. To do that, you'd want f[5::-1], which returns the string "raboof".


You also asked:

I have read start should not pass stop. is that true in case of negative step value also?

No, it's not true. Normally, the start value shouldn't pass the stop value, but only if the step is positive. If the step is negative, then the reverse is true. The start must, by necessity, be higher then the stop value.




回答2:


You can think like that:

with f[0:5], 0 is the start position and 5-1 the end position.

with f[0:5:-1], 5 is the start position and 0+1 the end position.

In slicing the start position must be lower than the end position. When this is not the case the result is an empty string. Thus f[0:5:-1] returns an empty string.



来源:https://stackoverflow.com/questions/19044559/understanding-negative-slice-step-value

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