string – What does n[::-1] means in Python?

string – What does n[::-1] means in Python?

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

string – What does n[::-1] means in Python?

Leave a Reply

Your email address will not be published. Required fields are marked *