Reputation: 11445
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*k
such that0 <= n < (j-i)/k
. In other words, the indices arei
,i+k
,i+2*k
,i+3*k
and 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) - 1
if 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.
Upvotes: 1
Views: 136
Reputation: 326
#something like this?
x='my test string'
print(x[3:7][::-1])
Upvotes: 1
Reputation: 77850
my_str[6:0-1:-1] # does NOT work
''
my_str[6:-1:-1] # also does NOT work
''
Yes, they do work -- as documented. A negative index is the sequence position, counting from the right. These expressions are equivalent to
my_str[6:-1:-1]
Since 6
and -1
denote the same position, the result is an empty string. However, if you give a value that is at or past the string start, such as
my_str[6:-10:-1]
then you see the expected reversal, just as if you'd specified 6::-1
Yes, you have to make a special case for the discontinuity in indexing.
Upvotes: 3