DavidK DavidK - 6 months ago 36
Python Question

Getting an IndexError: string index out of range

I'm not sure why I'm getting an

IndexError: string index out of range

with this code.

s = 'oobbobobo'
a = 0
for b in range(len(s)-1):
if (s[b] == 'b') and (s[b+1] == 'o') and (s[b+2] == s[b]):
a += 1
elif (s[b] == 'b') and (s[b+1] == 'o') and None:

print("Number of times bob occurs is: ", a)

I thought the
statement would fix the error, so I'm lost.


In this case, the length of s is 9 which means that you're looping over range(8) and therefore the highest value that b will have is 7 (Stay with me, I'm going somewhere with this ...)

When b = 7 (on the last iteration of the loop), the conditional expression in the if statement is being checked which contains:

(s[b+2] == s[b])

Well, since b = 7, b + 2 = 9, but s[9] will be out of bounds (remember, python is 0 indexed so the highest index in a a string of length 9 is 8).

I'm guessing that the fix is to just modify the range statement:

for b in range(len(s)-2):