问题
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