Count number of occurrences of a given substring in a string

后端 未结 30 1634
不思量自难忘°
不思量自难忘° 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条回答
  •  囚心锁ツ
    2020-11-22 14:59

    To find overlapping occurences of a substring in a string in Python 3, this algorithm will do:

    def count_substring(string,sub_string):
        l=len(sub_string)
        count=0
        for i in range(len(string)-len(sub_string)+1):
            if(string[i:i+len(sub_string)] == sub_string ):      
                count+=1
        return count  
    

    I myself checked this algorithm and it worked.

提交回复
热议问题