String count with overlapping occurrences

前端 未结 22 3402
耶瑟儿~
耶瑟儿~ 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-21 23:41

    My answer, to the bob question on the course:

    s = 'azcbobobegghaklbob'
    total = 0
    for i in range(len(s)-2):
        if s[i:i+3] == 'bob':
            total += 1
    print 'number of times bob occurs is: ', total
    

提交回复
热议问题