This question already has an answer here:
- string count with overlapping occurrences 21 answers
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'.
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 ofs
:You can also use
enumerate
.Working example.
But the best way is this, however it does not work with overlapping strings:
Here, try this, handcrafted :)
Demo
Hope this helps!