String count with overlapping occurrences

前端 未结 22 3074
耶瑟儿~
耶瑟儿~ 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:54

    def occurance_of_pattern(text, pattern):
        text_len , pattern_len = len(text), len(pattern)
        return sum(1 for idx in range(text_len - pattern_len + 1) if text[idx: idx+pattern_len] == pattern) 
    

提交回复
热议问题