extended slicing with string in python
python, slice
Solution
According to the documentation (emphasis added):
The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). If i or j is greater than len(s), use len(s). If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.
This means that if the slice stride is positive, an ommited slice start is the start of the sequence and an omitted slice end is the end of the sequence. If the slice stride is negative, it is the opposite. You can see this if you fill in one of the two values:
>>> '0123456'[:3]
'012'
>>> '0123456'[:3:-1]
'654'
>>> '0123456'[3:]
'3456'
>>> '0123456'[3::-1]
'3210'
One way to think of this is to visualize the sequence as a loop, where the start and end are the same point. When you omit one end of the slice, you are just specifying to use this "both-ends-point" as an endpoint, but not which direction to go from there. It is the stride sign that tells you which way to go, and this determines whether you are treating the "both-ends-point" as the beginning or the end of the sequence.
Problem
``` >>>"helloworld"[::1] 'helloworld' >>>"helloworld"[::-1] 'dlrowolleh' ``` according to the syntax `str[start:end:step]`. the start is by default 0 in both the cases. in first case the string is printed from index value 0. but in second case the string is printed from index value -1. and my question is why is string printed from -1 in the later case and why it is so ?