Overlapping count of substring in a string in Python

后端 未结 8 2176
北恋
北恋 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条回答
  •  萌比男神i
    2021-01-07 04:25

    Here, using re.finditer() is the best way to achieve what you want.

    import re 
    
    def get_substring_count(s, sub_s):
        return sum(1 for m in re.finditer('(?=%s)' % sub_s, s))
    
    get_substring_count('ababaa', 'aba')
    # 2 as response
    

提交回复
热议问题