4

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').

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Ryan Drake
  • 623
  • 3
  • 9
  • 30

6 Answers6

9

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
RickyA
  • 15,465
  • 5
  • 71
  • 95
2

How about something like this?

>>> d = {}
>>> string = 'hannahannahskdjhannahannah'
>>> for i in xrange(0,len(string)-len('hannah')+1):
...     if string[i:i+len('hannah')] == 'hannah':
...             d['hannah'] = d.get('hannah',0)+1
... 
>>> d
{'hannah': 4}
>>> 

This searches the string for hannah by splicing the string iteratively from index 0 all the way up to the length of the string minus the length of hannah

Harpal
  • 12,057
  • 18
  • 61
  • 74
1
'''
s: main string
sub: sub-string
count: number of sub-strings found
p: use the found sub-string's index in p for finding the next occurrence of next sub-string
'''
count=0
p=0
for letter in s:
    p=s.find(sub,p)   
    if(p!=-1):
        count+=1
        p+=1
print count
gopi m
  • 11
  • 2
0

If you want to count also nonconsecutive substrings, this is the way to do it

def subword(lookup,whole):
    if len(whole)<len(lookup):
          return 0
    if lookup==whole:
          return 1
    if lookup=='':
          return 1
    if lookup[0]==whole[0]:
         return subword(lookup[1:],whole[1:])+subword(lookup,whole[1:])
    return subword(lookup,whole[1:])
Uri Goren
  • 13,386
  • 6
  • 58
  • 110
0
def Count_overlap(string, substring):   
    count = 0
    start = 0
 
    while start < len(string):
        pos = string.find(substring, start)
  
        if pos != -1:
            start = pos + 1
            count += 1
        else:
            break
    return count
string = "hannahannahskdjhannahannah"
print(Count_overlap(string, "hannah"))
  • Could you provide a more detailed explanation for your code and how this resolves the question being asked? – Skully May 27 '21 at 21:34
-2

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.

NDevox
  • 4,056
  • 4
  • 21
  • 36
  • 3
    Either give a complete answer, or make a comment. – RickyA Sep 08 '14 at 10:17
  • Agreed Ricky, not helpful at all. – Ryan Drake Sep 08 '14 at 10:25
  • 2
    I'll make a comment next time but still don't think it's a good idea to write someones code for them, otherwise no one would learn anything. That said the accepted answer was literally an implementation of what I said. – NDevox Sep 08 '14 at 10:49
  • Yeah because Stackoverflow isn't a teaching resource, it's a Q&A. Sometimes a man just needs a fish, and has no desire to get up to their waist in water trying to figure out how a fishing pole works. – J.J May 01 '17 at 13:15