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

时间:2015-11-16 12:27:06

标签: python string indexing string-length indexoutofrangeexception

所以我让这个程序显示字符串中子字符串的位置。我现在正在正常工作(我希望),但由于某种原因,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

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

3 个答案:

答案 0 :(得分:4)

索引从0开始,您需要使用

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

答案 1 :(得分:1)

Python中的数组是零索引的。如果你有:

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

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

答案 2 :(得分:1)

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

数组始终以0开头编号,因此这应该可以解决问题:

c == word[n - 1]