Overlapping count of substring in a string in Python

后端 未结 8 2181
北恋
北恋 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: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.

提交回复
热议问题