简体   繁体   中英

Why doesn't my string reversal my_str[len(my_str)-1:-1:-1] produce output?

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? Ie, 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 index x = i + n*k such that 0 <= n < (ji)/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). When k is positive, i and j are reduced to len(s) if they are greater. When k is negative, i and j are reduced to len(s) - 1 if they are greater. 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.

However, this mentions nothing about a negative j being maximized to zero, which it appears is the current behavior.

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.

#something like this?
x='my test string'
print(x[3:7][::-1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM