Overlapping count of substring in a string in Python

后端 未结 8 2166
北恋
北恋 2021-01-07 03:42

I want to find all the counts (overlapping and non-overlapping) of a sub-string in a string. I found two answers one of which is using regex which is not my intention and t

8条回答
  •  無奈伤痛
    2021-01-07 04:32

    def sliding(a, n):
        return (a[i:i+n] for i in xrange(len(a) - n + 1))
    
    def substring_count(a, b):
        return sum(s == b for s in sliding(a, len(b)))
    
    assert list(sliding('abcde', 3)) == ['abc', 'bcd', 'cde']    
    assert substring_count('ababaa', 'aba') == 2
    

提交回复
热议问题