Count number of occurrences of a given substring in a string

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

    Overlapping occurences:

    def olpcount(string,pattern,case_sensitive=True):
        if case_sensitive != True:
            string  = string.lower()
            pattern = pattern.lower()
        l = len(pattern)
        ct = 0
        for c in range(0,len(string)):
            if string[c:c+l] == pattern:
                ct += 1
        return ct
    
    test = 'my maaather lies over the oceaaan'
    print test
    print olpcount(test,'a')
    print olpcount(test,'aa')
    print olpcount(test,'aaa')
    

    Results:

    my maaather lies over the oceaaan
    6
    4
    2
    

提交回复
热议问题