What\'s the best way to count the number of occurrences of a given string, including overlap in Python? This is one way:
def function(string, str_to_search_f
A simple way to count substring occurrence is to use count()
:
>>> s = 'bobob'
>>> s.count('bob')
1
You can use replace ()
to find overlapping strings if you know which part will be overlap:
>>> s = 'bobob'
>>> s.replace('b', 'bb').count('bob')
2
Note that besides being static, there are other limitations:
>>> s = 'aaa'
>>> count('aa') # there must be two occurrences
1
>>> s.replace('a', 'aa').count('aa')
3