所以我正在制作这个程序来显示字符串中子字符串的位置。我的元组现在可以正常工作(我希望如此),但由于某种原因,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
如果这是我的另一个愚蠢错误,我深表歉意。