Count number of occurrences of a given substring in a string

后端 未结 30 2054
不思量自难忘°
不思量自难忘° 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:33

    For a simple string with space delimitation, using Dict would be quite fast, please see the code as below

    def getStringCount(mnstr:str, sbstr:str='')->int:
        """ Assumes two inputs string giving the string and 
            substring to look for number of occurances 
            Returns the number of occurances of a given string
        """
        x = dict()
        x[sbstr] = 0
        sbstr = sbstr.strip()
        for st in mnstr.split(' '):
            if st not in [sbstr]:
                continue
            try:
                x[st]+=1
            except KeyError:
                x[st] = 1
        return x[sbstr]
    
    s = 'foo bar foo test one two three foo bar'
    getStringCount(s,'foo')
    

提交回复
热议问题