Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

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

So I'm making this program to display the positions of a substring in a string. I have the tuples working properly now (I hope), but for some reason python's giving me an error saying my index is out of range:

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

But as you can see, I already verified it with len right before it evaluates the indexing:

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

My apologies if this is another stupid mistake on my part.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Indexing starts from 0, you need to use

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...