我正在看一段python视频,根据讲师的切片运算符逻辑,有一种情况不起作用。
step value can be either +ve or -ve
-----------------------------------------
if +ve then it should be forward direction (L to R)
if -ve then it should be backward direction(R to L)
if +ve forward direction from begin to end-1
if -ve backward direction from begin to end + 1
in forward direction
-------------------------------
default : begin : 0
default : end : length of string
default step : 1
in backward direction
---------------------------------
default begin : -1
default end : -(len(string) + 1)
我尝试在python idle上运行satement,得到以下结果:
>>> x = '0123456789'
>>> x[2:-1:-1]
''
>>> x[2:0:-1]
'21'
根据规则,我应该得到'210'
的结果,但我得到的是''
。
发布于 2019-05-21 15:00:20
索引2:-1:-1
将扩展到2:9:-1
。负的开始或停止索引总是扩展到len(sequence) + index
。len('0123456789') + (-1)
为9。不能以-1的步长从2到9,因此结果为空。
取而代之的是,使用2::-1
一个空的(或None
)停止索引意味着“全部抓取”。当strep大小为负值时,空停止索引的默认值是-len(sequence) - 1
,它也是-(len(sequence) + 1)
,以抵消停止索引始终是独占的事实。
https://stackoverflow.com/questions/56241070
复制相似问题