String count with overlapping occurrences

前端 未结 22 3016
耶瑟儿~
耶瑟儿~ 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-21 23:36

    This is another example of using str.find() but a lot of the answers make it more complicated than necessary:

    def occurrences(text, sub):
        c, n = 0, text.find(sub)
        while n != -1:
            c += 1
            n = text.find(sub, n+1)
        return c
    
    In []:
    occurrences('1011101111', '11')
    
    Out[]:
    5
    

提交回复
热议问题