2

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:
        break 

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

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

1
  • 1
    your for loop termination condition is wrong, it should be: for b in range(len(s)-3): Commented Sep 8, 2016 at 3:16

1 Answer 1

3

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):
    ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.