Overlapping count of substring in a string in Python

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

    Looping through sliced string

    def count_substring(string, sub_string):
        l = len(sub_string)
        n = len(string)
        count = sum(1 for i in range(n-l+1) if string[i:i+l].count(sub_string)>0 )
        return count
    

提交回复
热议问题