Overlapping count of substring in a string in Python

后端 未结 8 2128
北恋
北恋 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
    
    0 讨论(0)
  • 2021-01-07 04:33

    Does this do the trick?

    def count(string, substring):
        n = len(substring)
        cnt = 0
        for i in range(len(string) - n):
            if string[i:i+n] == substring:
                cnt += 1
        return cnt
    
    print count('ababaa', 'aba') # 2
    

    I don't know if there's a more efficient solution, but this should work.

    0 讨论(0)
提交回复
热议问题