Search code examples
pythonstringslicereverseindices

How to reverse a string using explicit "slice of s from i to j with step k"?


I've seen that ::-1 can be used to reverse a string, but I thought it would be of interest to find the explicit integers i:j:k that would do the job.

I found the documentation common-sequence-operations, but can't get it to work. This code test comes up short:

s = "abcd"
print(1,s[4:3:-1]) 
print(2,s[4:2:-1])    
print(3,s[4:1:-1])
print(4,s[4:0:-1])
print(5,s[4:-1:-1])  

Here is the output:

1 
2 d
3 dc
4 dcb
5 

It looks like you can't do this with an explicit formula, s[i:j:k].

Usually I can figure out simple programming by trial-n-error, but that is not working here. Maybe a careful read of the documentation will get me over this!


Solution

  • You would have to do it like this:

    s = "abcd"
    print(s[len(s):-len(s)-1:-1])
    

    Or, as pointed out by Terry Jan Reedy in the comments, the following way of writing it illustrates nicely the length of the slice as (stop - start) / step:

    print(s[-1:-1-len(s):-1])
    

    The issue is that negative indexing starts at the back, so the negative indexes correspond the following "real" indexes:

    -1 ->  3
    -2 ->  2
    -3 ->  1
    -4 ->  0  # -len(s)
    -5 -> -1  # that's the one you need (or any smaller number)
    

    0 or -len(s) is not enough since the stop index of the slice is exclusive, so you have to get one lower.