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?
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?
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