iamryandrake iamryandrake - 23 days ago 7
Python Question

Python: Count overlapping substring in a string

Say I have

string = 'hannahannahskdjhannahannah'
and I want to count the number of times the string
hannah
occurs, I can't simply use count, because that only counts the substring once in each case.

Ie.

I am expecting to return
4
but only returns
2
when I run this in pyCharm with
string.count('hannah')

Answer

You could use a running index to fetch the next occurance:

bla = 'hannahannahskdjhannahannah'
cnt = 0
idx = 0
while True:
    idx = bla.find('hannah', idx)
    if idx >= 0:
        cnt += 1
        idx += 1
    else:
        break
print(cnt)

Gives:

>> 4