Python 说字符串索引超出范围,当我确认它不是

Python saying string index is out of range when I verified that it isn't

所以我正在制作这个程序来显示字符串中子字符串的位置。我现在让元组正常工作(我希望),但出于某种原因 python 给我一个错误,说我的索引超出范围:

Traceback (most recent call last):
  File "prog.py", line 11, in <module>
IndexError: string index out of range

但是如您所见,我已经在评估索引之前用 len 对其进行了验证:

sentence = "one two three one four one"
word = "one"

tracked = ()
n = 0
p = 0
for c in sentence:
    if n == 0 and c == word[n]:
        n += 1
        tracked = (p,)
    elif n == len(word) and c == word[n]: #Line 11 is right here
        print(tracked[0], tracked[1])
        tracked = ()
        n = 0
    elif c == word[n]:
        n += 1
        tracked = (tracked[0], p)
    else:
        tracked = ()
        n = 0
    p += 1

如果这是我的另一个愚蠢错误,我深表歉意。

索引从0开始,需要使用

elif n == len(word) and c == word[n - 1]:

Python 中的数组是零索引的。因此,如果您有:

a = "Some String"
n = len(a)
a[n]

这是无效的,因为 a 的唯一有效索引是 [0:n-1]

错误发生是因为 c == word[n] 超出范围。

数组总是从 0 开始索引,因此这应该可以解决问题:

c == word[n - 1]