String count with overlapping occurrences

前端 未结 22 3075
耶瑟儿~
耶瑟儿~ 2020-11-21 23:25

What\'s the best way to count the number of occurrences of a given string, including overlap in Python? This is one way:

def function(string, str_to_search_f         


        
22条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 00:01

    Here is my edX MIT "find bob"* solution (*find number of "bob" occurences in a string named s), which basicaly counts overlapping occurrences of a given substing:

    s = 'azcbobobegghakl'
    count = 0
    
    while 'bob' in s:
        count += 1 
        s = s[(s.find('bob') + 2):]
    
    print "Number of times bob occurs is: {}".format(count)
    

提交回复
热议问题