String count with overlapping occurrences

前端 未结 22 3445
耶瑟儿~
耶瑟儿~ 2020-11-21 23:25

What\'s the best way to count the number of occurrences of a given string, including overlap in Python? This is one way:

def function(string, str_to_search_f         


        
22条回答
  •  情歌与酒
    2020-11-22 00:01

    def count_overlaps (string, look_for):
        start   = 0
        matches = 0
    
        while True:
            start = string.find (look_for, start)
            if start < 0:
                break
    
            start   += 1
            matches += 1
    
        return matches
    
    print count_overlaps ('abrabra', 'abra')
    

提交回复
热议问题