为什么索引超出范围的子字符串切片会起作用? [英] Why does substring slicing with index out of range work?
问题描述
为什么 'example'[999:9999]
不会导致错误?既然 'example'[9]
这样做了,那么它背后的动机是什么?
根据这种行为,我可以假设 'example'[3]
本质上/内部与 'example'[3:4]
不同,即使虽然两者都产生相同的 'm'
字符串.
你说得对!'example'[3:4]
和 'example'[3]
根本不同,在序列边界之外切片(至少对于内置函数)不会不会导致错误.
一开始可能会让人感到惊讶,但仔细想想却是有道理的.索引返回单个项目,但切片返回项目的子序列.所以当你试图索引一个不存在的值时,没有什么可以返回的.但是当你在边界之外对一个序列进行切片时,你仍然可以返回一个空序列.
这里令人困惑的部分原因是字符串的行为与列表略有不同.看看当你对一个列表做同样的事情时会发生什么:
<预><代码>>>>[0, 1, 2, 3, 4, 5][3]3>>>[0, 1, 2, 3, 4, 5][3:4][3]这里的区别很明显.在字符串的情况下,结果似乎是相同的,因为在 Python 中,没有字符串之外的单个字符这样的东西.单个字符只是一个 1 个字符的字符串.
(有关在序列范围之外进行切片的确切语义,请参阅 mgilson 的回答.)
Why doesn't 'example'[999:9999]
result in error? Since 'example'[9]
does, what is the motivation behind it?
From this behavior I can assume that 'example'[3]
is, essentially/internally, not the same as 'example'[3:4]
, even though both result in the same 'm'
string.
You're correct! 'example'[3:4]
and 'example'[3]
are fundamentally different, and slicing outside the bounds of a sequence (at least for built-ins) doesn't cause an error.
It might be surprising at first, but it makes sense when you think about it. Indexing returns a single item, but slicing returns a subsequence of items. So when you try to index a nonexistent value, there's nothing to return. But when you slice a sequence outside of bounds, you can still return an empty sequence.
Part of what's confusing here is that strings behave a little differently from lists. Look what happens when you do the same thing to a list:
>>> [0, 1, 2, 3, 4, 5][3]
3
>>> [0, 1, 2, 3, 4, 5][3:4]
[3]
Here the difference is obvious. In the case of strings, the results appear to be identical because in Python, there's no such thing as an individual character outside of a string. A single character is just a 1-character string.
(For the exact semantics of slicing outside the range of a sequence, see mgilson's answer.)
这篇关于为什么索引超出范围的子字符串切片会起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!