Python: Count overlapping substring in a string

后端 未结 5 1276
情歌与酒
情歌与酒 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 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
    

提交回复
热议问题