Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlapping count of substring in a string in Python

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 the other was much more in-efficient than I need. I need something like:

'ababaa'.count('aba') == 2

str.count() just counts simple substrings. What should I do?

like image 813
lavee_singh Avatar asked Sep 18 '26 16:09

lavee_singh


2 Answers

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
like image 152
Chris Martin Avatar answered Sep 20 '26 05:09

Chris Martin


count = len(set([string.find('aba',x) for x in range(len(string)) if string.find('aba',x) >= 0]))
like image 42
rhozzy Avatar answered Sep 20 '26 06:09

rhozzy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!