Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count overlapping substring in a string [duplicate]

Tags:

python

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. That is, I am expecting to return 4 but only returns 2 when I run this with string.count('hannah').

like image 449
Ryan Drake Avatar asked Oct 27 '25 10:10

Ryan Drake


1 Answers

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
like image 72
RickyA Avatar answered Oct 29 '25 23:10

RickyA



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!