String count with overlapping occurrences

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

    Python's str.count counts non-overlapping substrings:

    In [3]: "ababa".count("aba")
    Out[3]: 1
    

    Here are a few ways to count overlapping sequences, I'm sure there are many more :)

    Look-ahead regular expressions

    How to find overlapping matches with a regexp?

    In [10]: re.findall("a(?=ba)", "ababa")
    Out[10]: ['a', 'a']
    

    Generate all substrings

    In [11]: data = "ababa"
    In [17]: sum(1 for i in range(len(data)) if data.startswith("aba", i))
    Out[17]: 2
    

提交回复
热议问题