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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…