简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM