Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字符串范围不生成最后一个字符_Python - Fatal编程技术网

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