How can I count the number of times a given substring is present within a string in Python?
For example:
>>> \'foo bar foo\'.numberOfOccurre
For overlapping count we can use use:
def count_substring(string, sub_string): count=0 beg=0 while(string.find(sub_string,beg)!=-1) : count=count+1 beg=string.find(sub_string,beg) beg=beg+1 return count
For non-overlapping case we can use count() function:
string.count(sub_string)