当循环变量在for循环中到达范围末尾时,这段代码如何不出现索引错误?

How does this code not get an index error when the loop variable gets to the end of the range in a for loop?

这是 edX 中的硬件问题,要求我确定单词 "bob" 在某个字符串中出现了多少次。我找到了解决方案,但我对它为何起作用感到困惑。对于代码(1):

代码(1)

s = 'azcbobobegghakl'
count = 0
for i in range(len(s)):
    if s[i:i+3] == "bob":
        count += 1
print(count)

在同一个硬件中,有一个问题要求我在某个字符串中按字母顺序找到最长的子字符串。在开始寻找解决方案时,我遇到了索引错误,因为我试图引用一个超出范围的索引;此代码中显示:

代码(2)

s = 'azcbobobegghakl'
temp = ''
longest = ''
for i in range(len(s)):
    if s[i] <= s[i+1]:
        temp += s[i+1]
        if len(temp) > len(longest):
            longest = temp
    else:
        temp = s[i+1]
print(longest)

错误(2)

Traceback (most recent call last):
  File "C:/Users/vchi/PycharmProjects/edX/introduction.py", line 5, in <module>
    if s[i] <= s[i+1]:
IndexError: string index out of range

为什么当 i > len(s)-4 和 s[i:i+3] 尝试引用时,CODE(1) 不会遇到与 CODE(2) 收到的相同类型的错误对于超出范围的事情?提前致谢!

Python 切片在很多方面都很奇怪,这就是一种证明。

对于 python 中的字符串,如果切片超出范围,它只会将切片的 "end" 设置为最后一个可行索引,因此如果我们执行类似以下操作:

a = 'boboabcdef'

然后做了:

b = a[4:12]

我们只会得到 b 等于 'abcdef',因为它会忽略字符串的其余部分。

但是当谈到列表的索引时,python 有更严格的解释,因为调试一个列表可能超出索引而没有错误或警告的程序将非常困难。