String count with overlapping occurrences

前端 未结 22 3403
耶瑟儿~
耶瑟儿~ 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:51

    A simple way to count substring occurrence is to use count():

    >>> s = 'bobob'
    >>> s.count('bob')
    1
    

    You can use replace () to find overlapping strings if you know which part will be overlap:

    >>> s = 'bobob'
    >>> s.replace('b', 'bb').count('bob')
    2
    

    Note that besides being static, there are other limitations:

    >>> s = 'aaa'
    >>> count('aa') # there must be two occurrences
    1 
    >>> s.replace('a', 'aa').count('aa')
    3
    

提交回复
热议问题