1
    s = 'gfdhbobobyui'
    bob = 0
    for x in range(len(s)):
         if x == 'bob':
             bob += 1
    print('Number of times bob occurs is: ' + str(bob))

Attempting to write a code that will count the amount of times 'bob' appears in s, but for some reason this always outputs 0 for number of 'bob'.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Patrick Hayes
  • 23
  • 1
  • 2
  • 5

3 Answers3

3

Here, try this, handcrafted :)

for i, _ in enumerate(s): #i here is the index, equal to "i in range(len(s))"
    if s[i:i+3] == 'bob': #Check the current char + the next three chars.
        bob += 1
print('Number of times bob occurs is: ' + str(bob))

Demo

>>> s = 'gfdhbobobyui'
>>> bob = 0
>>> for i, v in enumerate(s): #i here is the index, equal to "i range(len(s))"
    if s[i:i+3] == 'bob': #Check the current char + the next two chars.
        bob += 1


>>> bob
2

Hope this helps!

aIKid
  • 26,968
  • 4
  • 39
  • 65
3

x is a number, it can't be equal to 'bob'. That's why it always output 0.

You should use x in order to get a substring of s:

bob = 0
for x in range(len(s) - 2):
    if s[x:x+3] == 'bob':
        bob += 1

You can also use enumerate.

Maxime Chéramy
  • 17,761
  • 8
  • 54
  • 75
2
s = 'gfdhbobobyui'
bob = 0
for x in range(len(s)):
     if s[x:x+3] == 'bob':  # From x to three 3 characters ahead.
         bob += 1
print('Number of times bob occurs is: ' + str(bob))

Working example.

But the best way is this, however it does not work with overlapping strings:

s.ount('bob')
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199