为什么以下情况下的切片运算符在python中不起作用?

时间:2019-05-21 14:55:38

标签: python python-3.x

我当时正在观看一个python视频,根据讲师对slice运算符的逻辑,有一种情况没有用。

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上运行卫星,并得到以下结果:

>>> x = '0123456789'
>>> x[2:-1:-1]
''
>>> x[2:0:-1]
'21'

根据规则,我应该得到'210'的结果,但是我得到''

1 个答案:

答案 0 :(得分:1)

索引2:-1:-1扩展为2:9:-1。负起始索引或终止索引会始终扩展为len(sequence) + indexlen('0123456789') + (-1)是9。您无法以-1的步长从2到9,因此结果为空。

相反,使用2::-1为空(或None)停止索引意味着“全部抓住”。当链球菌大小为负时,空停止索引的默认值为-len(sequence) - 1,也为-(len(sequence) + 1),以抵消停止索引为总是排他的的事实。 >