Count number of occurrences of a given substring in a string

后端 未结 30 2003
不思量自难忘°
不思量自难忘° 2020-11-22 13:58

How can I count the number of times a given substring is present within a string in Python?

For example:

>>> \'foo bar foo\'.numberOfOccurre         


        
30条回答
  •  Happy的楠姐
    2020-11-22 14:35

    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)
    

提交回复
热议问题