Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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_String - Fatal编程技术网

对python字符串使用切片运算符[:]不会导致越界错误

对python字符串使用切片运算符[:]不会导致越界错误,python,string,Python,String,我刚刚开始学习python,当时正在使用slice(:)操作符和字符串。出于某种原因,如果我指定一个无效的索引,后跟slice操作符,它不会给出“超出范围”错误 >>s='Hello' >>>打印s[5] 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 索引器错误:字符串索引超出范围 >>>打印s[5:] //只打印一个换行符,没有错误 有人能解释为什么我在第二种情况下没有出错。来自以下文档: 退化切片索引处理得很优雅:太大的索引将替换为字符串大小,小于下限的上界将返回空字符串 换句话说

我刚刚开始学习python,当时正在使用slice(:)操作符和字符串。出于某种原因,如果我指定一个无效的索引,后跟slice操作符,它不会给出“超出范围”错误

>>s='Hello'
>>>打印s[5]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
索引器错误:字符串索引超出范围
>>>打印s[5:]
//只打印一个换行符,没有错误
有人能解释为什么我在第二种情况下没有出错。

来自以下文档:

退化切片索引处理得很优雅:太大的索引将替换为字符串大小,小于下限的上界将返回空字符串

换句话说:索引可能太大,但在这种情况下,它会被字符串大小替换


请注意,您的字符串
s
有五个字符,因此
s[5://code>与调用
s[len(s):]
相同,这与获取空字符串相同(因为缺少的上限默认为
len(s)
,因此它最终变成
s[len(s):len(s)]

,切片从不导致越界异常。
>>> s='Hello'
>>> print s[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range

>>> print s[5:]
//Prints just a newline, no error