Number of occurrences of a substring in a string

前端 未结 6 1564
死守一世寂寞
死守一世寂寞 2020-12-12 04:08

I need to count the nunber of times the substring \'bob\' occurs in a string.

Example problem: Find the number of times \'bob\' occurs in string s such

6条回答
  •  情书的邮戳
    2020-12-12 05:01

    Here you have an easy function for the task:

    def countBob(s):
    number=0
    while s.find('Bob')>0:
        s=s.replace('Bob','',1)
        number=number+1        
    return number
    

    Then, you ask countBob whenever you need it:

    countBob('This Bob runs faster than the other Bob dude!')
    

提交回复
热议问题