How can I count the number of times a given substring is present within a string in Python?
For example:
>>> \'foo bar foo\'.numberOfOccurre
Risking a downvote because 2+ others have already provided this solution. I even upvoted one of them. But mine is probably the easiest for newbies to understand.
def count_substring(string, sub_string):
slen = len(string)
sslen = len(sub_string)
range_s = slen - sslen + 1
count = 0
for i in range(range_s):
if (string[i:i+sslen] == sub_string):
count += 1
return count