TL;DR: Why doesn't my_str[6:-1:-1] work while my_str[6::-1] does?
I have a string:
my_str="abcdefg"
I have to reverse parts of the string, which I generally do with
my_str[highest_included_index:lowest_included_index-1:-1]
For example,
# returns the reverse of all values between indices 2 and 6 (inclusive)
my_str[6:2-1:-1]
'gfedc'
This pattern breaks down if I want to include the 0 index in my reversal:
my_str[6:0-1:-1] # does NOT work
''
my_str[6:-1:-1] # also does NOT work
''
my_str[6::-1] # works as expected
'gfedcba'
Do I have to add an edge case that checks if the lowest index I want to include in a reversed string is zero and not include it in my reversal? I.e., do I have to do
for low in range(0,5):
if low == 0:
my_str[6::-1]
else:
my_str[6:low-1:-1]
That seems... unwieldy and not what I expect from python.
Edit:
The closest thing I could find to documentation of this is here:
s[i:j:k]
...
The slice of s from i to j with step k is defined as the sequence of items with indexx = i + n*ksuch that0 <= n < (j-i)/k. In other words, the indices arei,i+k,i+2*k,i+3*kand so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced tolen(s)if they are greater. When k is negative, i and j are reduced tolen(s) - 1if they are greater. If i or j are omitted orNone, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k isNone, it is treated like 1.
However, this mentions nothing about a negative j being maximized to zero, which it appears is the current behavior.