Understanding string reversal via slicing
The "-1" part represents the "step" part of the slicing—in this case, it goes through the string 1 character at a time, but backwards (a negative step means start from the end of the string). If you specify the step to be 2, for instance, you would get every other character of the string, starting with the first one. If you specify a step of -2, then you'd get every other character of the string, starting with the last character and working backwards.
So, in a nutshell, if a = '12345'
:
a[::2]
becomes135
a[::-1]
becomes54321
a[::-2]
becomes531
I think the following makes a bit more sense for print strings in reverse, but maybe that's just me:
for char in reversed( myString ):
print( char, end = "" )
Sure, the [::]
is the extended slice operator. It allows you to take substrings. Basically, it works by specifying which elements you want as [begin:end:step], and it works for all sequences. Two neat things about it:
- You can omit one or more of the elements and it does "the right thing"
- Negative numbers for begin, end, and step have meaning
For begin and end, if you give a negative number, it means to count from the end of the sequence. For instance, if I have a list:
l = [1,2,3]
Then l[-1]
is 3, l[-2]
is 2, and l[-3]
is 1.
For the step
argument, a negative number means to work backwards through the sequence. So for a list::
l = [1,2,3,4,5,6,7,8,9,10]
You could write l[::-1]
which basically means to use a step size of -1 while reading through the list. Python will "do the right thing" when filling in the start and stop so it iterates through the list backwards and gives you [10,9,8,7,6,5,4,3,2,1]
.
I've given the examples with lists, but strings are just another sequence and work the same way. So a[::-1]
means to build a string by joining the characters you get by walking backwards through the string.