在玩数组切片时我注意到a[index:] or a[:index]
切片类型不会产生字符串的数组索引越界错误。
str = "abcde"
print str[10:]
print str[:10]
产生输出:
''
abcde
有人能解释一下为什么吗?它不应该产生数组索引越界错误吗?如果我尝试执行以下操作,Python 确实会产生此错误:print str[10]
.
切片用于创建新列表。如果索引不在列表中元素数量的范围内,我们可以返回一个空列表。所以,我们不必抛出错误。
但是,如果我们尝试访问列表中大于元素数量的元素,我们将无法返回任何默认值(甚至不能None
因为它可能是列表中的有效值)。因此
IndexError: list index out of range
被抛出。
切片时,如果起始索引大于等于序列长度,则返回序列的长度设置为0,在此line http://hg.python.org/cpython/file/3a1db0d2747e/Objects/sliceobject.c#l178
defstop = *step < 0 ? -1 : length;
...
if (r->stop == Py_None) {
*stop = defstop;
}
...
if ((*step < 0 && *stop >= *start)
|| (*step > 0 && *start >= *stop)) {
*slicelength = 0;
对于Strings,如果切片后返回的字符串长度为0,则返回空字符串,在这条线 http://hg.python.org/cpython/file/3a1db0d2747e/Objects/stringobject.c#l1318
if (slicelength <= 0) {
return PyString_FromStringAndSize("", 0);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)