python - 为什么 python 的列表切片不会产生索引越界错误?

标签 python string list python-2.7 slice

<分区>

在玩数组切片时,我注意到 a[index:] 或 a[:index] 类型的切片不会为字符串产生数组索引超出范围的错误。

str = "abcde"
print str[10:]
print str[:10]

产生输出:

''
abcde

谁能解释一下为什么?它不应该产生数组索引越界错误吗?如果我尝试执行以下操作,Python 确实会产生此错误:print str[10]

最佳答案

切片用于创建新列表。如果索引不在列表中元素数量的范围内,我们可以返回一个空列表。因此,我们不必抛出错误。

但是,如果我们尝试访问列表中大于元素数量的元素,我们不能返回任何默认值(甚至不能返回 None,因为它可能是列表)。这就是为什么

IndexError: list index out of range

被抛出。

切片时,如果起始索引大于等于序列长度,则返回序列的长度设置为0,在此line

defstop = *step < 0 ? -1 : length;
...
if (r->stop == Py_None) {
    *stop = defstop;
}
...
if ((*step < 0 && *stop >= *start)
    || (*step > 0 && *start >= *stop)) {
    *slicelength = 0;

对于String,如果切片后返回的字符串长度为0,则返回空字符串,在this line

if (slicelength <= 0) {
    return PyString_FromStringAndSize("", 0);
}

关于python - 为什么 python 的列表切片不会产生索引越界错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22951107/

相关文章:

python - 如何从 python 中的 RFC 2822 邮件 header 中提取多个电子邮件地址?

c# - 如何使用带有多个星号的行过滤器过滤 c# 数据表?

python - 比较两个列表的有效方法,记住每个唯一元素的来源

Java 数组列表 : Difference between Copy Constructor and Copying via assignment

python - 如何从排序列表中选择小于给定整数的元素?

python - OSError : [Errno 7] Argument list too long on ubuntu, python 使用 popen 调用 bitcoind-cli

python - pymongo中的多个查询

python - 用于谷歌应用引擎的 python 网络框架

python - 将列表转换为字符串并允许使用分隔符

java - 下一行间距问题