-1

I am trying to make a program that searches a string for 'bob' and prints the amount of times it appears. Here is the code:

s = 'mbobobboobooboo'
numbob = 0
for i in range(len(s) ) :
    u = s[i] 
    if u == 'o':
        g = i
        if g != 0 and g != len(s) :
            if (s[g+1]) == 'b' and (s[g-1]) == 'b': #this line is the problam
                numbob += 1
                print("Number of times bob occurs is: " +str(numbob) )

I am getting the string index out of range error and i cant seem to fix it. any suggestions

jrbedard
  • 3,662
  • 5
  • 30
  • 34
jon smith
  • 73
  • 1
  • 6

3 Answers3

3

Use

for i in range(len(s)-1) 

or

g!=len(s)-1

len() gives you the total number of characters, which will be the index of the character after the last one since indexing starts at 0.

You can get rid of the if g!=0 and g!=len(s) part all together if you use

for i in range(1,len(s)-1)
Saeid
  • 4,147
  • 7
  • 27
  • 43
SilentLupin
  • 658
  • 10
  • 16
0

When you make your condition :

if (s[g+1]) == 'b' and (s[g-1]) == 'b':

At the last element of your string, it is impossible to do s[g+1] because it is out of the string.

So you have to finish your loop just before the end. Like this for exemple :

for i in range(len(s)-1) :
acknowledge
  • 434
  • 6
  • 12
0

my solution would more easy than your. instead of divide letters 'b' 'o' 'b' . slice string s

countbob=0
bob='bob'
for i in range(len(s)):
       bob2=s[i:i+3]
       if bob2 == bob:
               countbob +=1
print ("Number of times bob occurs is: " + str(countbob))
tulgar
  • 1