String count with overlapping occurrences

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

    A fairly pythonic way would be to use list comprehension here, although it probably wouldn't be the most efficient.

    sequence = 'abaaadcaaaa'
    substr = 'aa'
    
    counts = sum([
        sequence.startswith(substr, i) for i in range(len(sequence))
    ])
    print(counts)  # 5
    

    The list would be [False, False, True, False, False, False, True, True, False, False] as it checks all indexes through the string, and because int(True) == 1, sum gives us the total number of matches.

提交回复
热议问题