How to count all occurrences of a word in a string using python

后端 未结 4 1448
栀梦
栀梦 2021-01-21 04:04

I\'m trying to find the number of times \'bob\' occurs in a string of characters like \'abdebobdfhbobob\'.

My code (that I found through another stackoverflow question)

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-21 04:23

    We can just check all possible candidates:

    def count_substrings(sub, main):
        n = len(sub)
        return sum(sub == main[i : i+n] for i in range(len(main) - n + 1))
    
    s = 'abdebobdfhbobob'
    sub = 'bob'
    print('The number of times %s occurs is: %d' % (sub, count_substrings(sub, s)))  # 3
    

提交回复
热议问题