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')
You could use a running index to fetch the next occurance:
Gives:
If you want to count also nonconsecutive substrings, this is the way to do it
Don't want to answer this for you as it's simple enough to work out yourself.
But if I were you I'd use the string.find() method which takes the string you're looking for and the position to start looking from, combined with a while loop which uses the result of the find method as it's condition in some way.
That should in theory give you the answer.
How about something like this?
This searches the
string
forhannah
by splicing the string iteratively from index 0 all the way up to the length of the string minus the length ofhannah