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
def count_substring(string, sub_string):
counter = 0
for i in range(len(string)):
if string[i:].startswith(sub_string):
counter = counter + 1
return counter
Above code simply loops throughout the string once and keeps checking if any string is starting with the particular substring that is being counted.