How can I count the number of times a given substring is present within a string in Python?
For example:
>>> \'foo bar foo\'.numberOfOccurre
You could use the startswith method:
def count_substring(string, sub_string): x = 0 for i in range(len(string)): if string[i:].startswith(sub_string): x += 1 return x