Count number of occurrences of a given substring in a string

后端 未结 30 2142
不思量自难忘°
不思量自难忘° 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:50

    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
    

提交回复
热议问题