简体   繁体   English

n[::-1] 在 Python 中是什么意思?

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

I have a string n = "abc" .我有一个字符串n = "abc"

I want to reverse it and found a solution like n[::-1] .我想扭转它并找到一个像n[::-1]的解决方案。

What is the meaning of all 3 arguments?所有 3 个参数的含义是什么?

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 :切片符号由三部分组成: startstopstep

>>> '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:如果不指定startstop ,则表示遍历整个序列:

>>> '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这在“ 理解切片符号”、“扩展切片”下的 Python 文档和这篇博文中得到了很好的解释: Python 切片示例:开始、停止和步骤

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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