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

后端 未结 4 1451
栀梦
栀梦 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:48

    Based on documentation, str.count() return the number of non-overlapping occurrences of substring sub in the range [start, end]. You can use a positive lookahead based regular expression in order to find the overlapped strings:

    >>> import re
    >>> s = 'abdebobdfhbobob'
    >>> len(re.findall(r'(?=bob)', s))
    3
    

    If you don't want to use regex you can use a generator expression within the sum() function that will iterate over the all sub-strings with length 3 and count the number of those that are equal to 'bob':

    >>> sum(s[i:i+3] == 'bob' for i in range(len(s)-2))
    3
    

提交回复
热议问题