I\'m trying to find the number of times \'bob\' occurs in a string of characters like \'abdebobdfhbobob\'.
My code (that I found through another stackoverflow question)
Based on documentation, str.count()
return the number of non-overlapping occurrences of substring sub in the range [start, end]
. You can use a positive lookahead based regular expression in order to find the overlapped strings:
>>> import re
>>> s = 'abdebobdfhbobob'
>>> len(re.findall(r'(?=bob)', s))
3
If you don't want to use regex you can use a generator expression within the sum()
function that will iterate over the all sub-strings with length 3 and count the number of those that are equal to 'bob':
>>> sum(s[i:i+3] == 'bob' for i in range(len(s)-2))
3