1

Assume s is a string of lower case characters.

Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print

Number of times bob occurs is: 2

This is my answer, but i dont know what's wrong with my code. Please help

s = "azcbobobegghakl"
coutBob=0
i=0
for char in range (len(s)):
    if char[i:i+3]=="bob":
        coutBob+=1
    else:
        i=i+1
print ("Number of times bob occurs is: " + str(coutBob))
  • 1
    This seems AWFULLY familiar...... https://stackoverflow.com/questions/19617125/python-slicing-bob-in-s – L_Church Jan 22 '18 at 16:40
  • 1
    Possible duplicate of [Python Slicing 'bob' in s](https://stackoverflow.com/questions/19617125/python-slicing-bob-in-s) – ti7 Jan 22 '18 at 16:46
  • Possible duplicate of [string count with overlapping occurrences](https://stackoverflow.com/questions/2970520/string-count-with-overlapping-occurrences) – Nathan Vērzemnieks Jan 22 '18 at 18:06

2 Answers2

0

You need to subscript the string s, not the index:

for i in range(len(s)):
    if s[i:i+3]=="bob":
        coutBob+=1
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

I think this will help you.

b = list(s)
i = 0
j = 0
for i in range(0,len(b)-2):
    if b[i]=='b' and b[i+1]=='o' and b[i+2]=='b':
       j = j + 1
print ("Number of times bob occurs is: %d"%j)
Shashank Singh
  • 719
  • 6
  • 11