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').
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With