If I have a string str1=boobbobobpzfsbobboobbobb and I want to count how many times the string 'bob' is present inside it. However, I cannot use str1.count as it only counts non overlapped strings. SO what do I do?
4 Answers
Using regular expression (positive lookahead assertion):
>>> import re
>>> str1 = 'boobbobobpzfsbobboobbobb'
>>> sum(1 for m in re.finditer('b(?=ob)', str1))
4
Comments
You can solve it in quadratic time (worst case) by considering all the substrings starting at an increasing index and counting how many start with "bob":
str1 = "boobbobobpzfsbobboobbobb"
times = 0
for pos in range(len(str1)):
if str1[pos:].startswith("bob"):
times += 1
print(times)
or:
str1 = "boobbobobpzfsbobboobbobb"
times = sum(1 for x in range(len(str1)) if str1[x:].startswith("bob"))
print(times)