String count with overlapping occurrences

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

    You can also try using the new Python regex module, which supports overlapping matches.

    import regex as re
    
    def count_overlapping(text, search_for):
        return len(re.findall(search_for, text, overlapped=True))
    
    count_overlapping('1011101111','11')  # 5
    

提交回复
热议问题