String count with overlapping occurrences

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

    >>> import re
    >>> text = '1011101111'
    >>> len(re.findall('(?=11)', text))
    5
    

    If you didn't want to load the whole list of matches into memory, which would never be a problem! you could do this if you really wanted:

    >>> sum(1 for _ in re.finditer('(?=11)', text))
    5
    

    As a function (re.escape makes sure the substring doesn't interfere with the regex):

    >>> def occurrences(text, sub):
            return len(re.findall('(?={0})'.format(re.escape(sub)), text))
    
    >>> occurrences(text, '11')
    5
    

提交回复
热议问题