I just started learning programming and I need some clarification.
For
s = "abcdef"
print(s[0:2:-1])
The output is an empty string. What I don't quite understand is why print(s[:2:-1]) has an output of fed, and print(s[0:2:-1]) does not.
print(s[:2:-1]) is not the same as print(s[0:2:-1]) - it's the same as print(s[None:2:-1]). When you leave out one of the slice parameters or use None, the endpoint is substituted. If the step size is negative, the start point is the end of the sequence and the end point is the start of the sequence. print(s[0:2:-1]) goes from s[0] to s[2], but it can't because 2 > 0 and there's no way to count backward from 0 to 2. print(s[:2:-1]) goes from s[-1] to s[2], because s[-1] is the last character of the string.
If you set the third parameter to be negative, the elements of the iterable will be traversed in reverse order. Then letting the first parameter be empty will mean that the iteration should start from the rightmost element. Think about the fact that s[::-1] == 'fedcba'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With