I was looking for a way to print a string backwards, and after a quick search on google, I found this method:
Suppose a
is a string variable. This will return the a
string backwards:
a[::-1]
Can anyone explain how that works?
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:
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.
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]
becomes 135
a[::-1]
becomes 54321
a[::-2]
becomes 531
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With