Python Question

Python IndexError: string index out of range

Can someone help me why is it saying: "IndexError: string index out of range"
When I add the "letterCount += 1" to the first else it makes this error, without it is working.

The goal is to count "bob"s in s.

Thanks!

s = 'oobobodobooobobobobabobbobbobobbobbobhbxbobbk'

vowelCount = 0
letterCount = 0
pointer = s

for pointer in s:
print(pointer)
if pointer == 'b':
print (str(letterCount) + '. betű B' )

if (s[letterCount+1] + s[letterCount+2]) == str('ob') :
vowelCount += 1
letterCount += 1
print( str(vowelCount) + '. BOB megtalálva')
else:
print('Nem OB jön utána')
letterCount += 1
else:
print(str(letterCount) + '. betű nem B')
letterCount += 1

print ("Number of times bob occurs is: " + str(vowelCount))

Answer

You need to check the string s length with something like:

letterCount+2 <= len(s) 

i.e.

s = 'oobobodobooobobobobabobbobbobobbobbobhbxbobbk'

vowelCount = 0
letterCount = 0
pointer = s

for pointer in s:  
    print(pointer)
    if pointer == 'b':
        print (str(letterCount) + '. betű B' )

        if (letterCount+2 <= len(s) and (s[letterCount+1] + s[letterCount+2]) == str('ob')) :
           vowelCount += 1
           letterCount += 1
           print( str(vowelCount) + '. BOB megtalálva')
        else:
           print('Nem OB jön utána')
           letterCount += 1
    else:      
        print(str(letterCount) + '. betű nem B')
        letterCount += 1

print ("Number of times bob occurs is: " + str(vowelCount))