Python: Count overlapping substring in a string

后端 未结 5 1273
情歌与酒
情歌与酒 2020-12-11 09:36

Say I have string = \'hannahannahskdjhannahannah\' and I want to count the number of times the string hannah occurs, I can\'t simply use count, bec

相关标签:
5条回答
  • 2020-12-11 09:57

    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
    
    0 讨论(0)
  • 2020-12-11 10:00

    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

    0 讨论(0)
  • 2020-12-11 10:01
    '''
    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
    
    0 讨论(0)
  • 2020-12-11 10:08

    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:])
    
    0 讨论(0)
  • 2020-12-11 10:15

    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.

    0 讨论(0)
提交回复
热议问题