1

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.

Bucket
  • 7,415
  • 9
  • 35
  • 45
Shi Libin
  • 29
  • 1
  • 1
    possible duplicate of [Python's slice notation](http://stackoverflow.com/questions/509211/pythons-slice-notation) – Bucket Oct 21 '13 at 15:28
  • This question is phrased in a way that'd make sense to someone who's not heard the term "slice notation", so I don't think it's an exact duplicate. – bouteillebleu Oct 21 '13 at 15:51

3 Answers3

4

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].

Community
  • 1
  • 1
2

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.

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
2

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.

Stephen Diehl
  • 8,271
  • 5
  • 38
  • 56