Python字符串范围不生成最后一个字符
单词Python字符串范围不生成最后一个字符,python,Python,单词Hello包含5个字符 >>> x = 'Hello' >>> >>> len(x) 5 >>> x[5]将产生一个错误,因为Python编号从0开始。我能理解这一点 >>> x[5] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index
Hello
包含5个字符
>>> x = 'Hello'
>>>
>>> len(x)
5
>>>
x[5]
将产生一个错误,因为Python编号从0开始。我能理解这一点
>>> x[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>>
>>> x[0]
'H'
>>>
但是,当我尝试从x[0:4]
开始的范围时,最后一个字母不在那里
>>> x[0:4]
'Hell'
>>>
我可以知道为什么吗?从0切片到4将生成项目0、1、2和3。如果要包含las,请使用一个
x[0:5]
意味着
不包括索引4
这背后有一个理由。您只需将这两个数字相减即可计算结果的长度。:) 在切片中,第一个int被包含,而最后一个int被排除我认为原因在于大多数操作的执行方式:
for(x=start;x<end;x++){
output[x]=input[x]
}
for(x=start;x为了记住这一点,你可以想象如下:
Word: | H | E | L | L | O |
Slice position: 0 1 2 3 4 5
Index position: 0 1 2 3 4
所以当你写下x[0:4]
python将返回Hell
但是当你写下x[0:5]
python将返回Hello
范围的上限被排除,可能的重复原理是你可以做x
对应于x[0:len(x)]
而不是len(x)-1
谢谢@George。是否可以用Python查看这种切片技术的实际源代码?如果可以,请告诉我实际代码是如何或在哪里。
for(x=start;x<end;x++){
output[x]=input[x]
}
Word: | H | E | L | L | O |
Slice position: 0 1 2 3 4 5
Index position: 0 1 2 3 4