8

I have a string n = "abc".

I want to reverse it and found a solution like n[::-1].

What is the meaning of all 3 arguments?

8-Bit Borges
  • 8,924
  • 25
  • 82
  • 157
Gourav Singla
  • 1,638
  • 1
  • 14
  • 18
  • 1
    @shiplu.mokadd.im: Perhaps `reversed` is faster, but it returns an iterator, not a string. – PM 2Ring Feb 16 '15 at 06:17
  • Reopened. This question asks specifically about the meaning of the slice notation which is different from the question in https://stackoverflow.com/questions/931092/reverse-a-string-in-python . That question is string specific and goal specific. This question just about the syntax. – Raymond Hettinger Jul 28 '17 at 23:18

1 Answers1

35

It means, "start at the end; count down to the beginning, stepping backwards one step at a time."

The slice notation has three parts: start, stop, step:

>>> 'abcdefghijklm'[2:10:3]  # start at 2, go upto 10, count by 3
'cfi'
>>> 'abcdefghijklm'[10:2:-1] # start at 10, go downto 2, count down by 1
'kjihgfed'

If the start and stop aren't specified, it means to go through the entire sequence:

>>> 'abcdefghijklm'[::3]  # beginning to end, counting by 3
'adgjm'
>>> 'abcdefghijklm'[::-3] # end to beginning, counting down by 3
'mjgda'

This is explained nicely in Understanding slice notation, in the Python docs under "extended slicing", and in this blogpost: Python Slice Examples: Start, Stop and Step

Trenton McKinney
  • 43,885
  • 25
  • 111
  • 113
Raymond Hettinger
  • 199,887
  • 59
  • 344
  • 454