Reputation: 29
Somebody told me you can reverse a string like this:
a='123456'
a = a[::-1]
print a
I just don't know how it works.
Upvotes: 1
Views: 136
Reputation: 8419
In Python negative slicing wraps around, so -1 is the last element.
[1,2,3,4][-1] = 4
In slice notation the first two elements are the bounds and the third is the index increment. By default the increment is 1.
[1,2,3,4,5][1:4] == [2,3,4]
[1,2,3,4,5][1:4:2] == [2,4]
Python also lets omit the bound indices to refer to the whole list [::]
.
[1,2,3,4,5][::1] == [1,2,3,4,5]
So if your increment is negative you reverse the list by indexing backwards from the end.
[1,2,3,4,5][::-1] == [5,4,3,2,1]
Strings implement the same iterable protocol as lists so instead of reversing elements in a list you are reversing characters in a string.
Upvotes: 2
Reputation: 304355
The third parameter is the step size. Try some different step sizes to get the idea
>>> a = '123456'
>>> a[::2]
'135'
>>> a[::3]
'14'
>>> a[::-3]
'63'
>>> a[::-2]
'642'
>>> a[::-1]
'654321'
Since the start and stop are left empty, Python will choose them to step along the whole string.
Upvotes: 2
Reputation:
That takes advantage of Python's slice notation. Basically, it returns a new string created by stepping backwards through the original string. See a demonstration below:
>>> mystr = "abcde"
>>> mystr[::-1]
'edcba'
>>> for i in mystr[::-1]:
... print i
...
e
d
c
b
a
>>>
The format for slice notation is [start:stop:step]
.
Upvotes: 4