Count number of occurrences of a given substring in a string

后端 未结 30 1990
不思量自难忘°
不思量自难忘° 2020-11-22 13:58

How can I count the number of times a given substring is present within a string in Python?

For example:

>>> \'foo bar foo\'.numberOfOccurre         


        
30条回答
  •  一整个雨季
    2020-11-22 14:40

    The current best answer involving method count doesn't really count for overlapping occurrences and doesn't care about empty sub-strings as well. For example:

    >>> a = 'caatatab'
    >>> b = 'ata'
    >>> print(a.count(b)) #overlapping
    1
    >>>print(a.count('')) #empty string
    9
    

    The first answer should be 2 not 1, if we consider the overlapping substrings. As for the second answer it's better if an empty sub-string returns 0 as the asnwer.

    The following code takes care of these things.

    def num_of_patterns(astr,pattern):
        astr, pattern = astr.strip(), pattern.strip()
        if pattern == '': return 0
    
        ind, count, start_flag = 0,0,0
        while True:
            try:
                if start_flag == 0:
                    ind = astr.index(pattern)
                    start_flag = 1
                else:
                    ind += 1 + astr[ind+1:].index(pattern)
                count += 1
            except:
                break
        return count
    

    Now when we run it:

    >>>num_of_patterns('caatatab', 'ata') #overlapping
    2
    >>>num_of_patterns('caatatab', '') #empty string
    0
    >>>num_of_patterns('abcdabcva','ab') #normal
    2
    

提交回复
热议问题