Count number of occurrences of a given substring in a string

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

    If you want to find out the count of substring inside any string; please use below code. The code is easy to understand that's why i skipped the comments. :)

    string=raw_input()
    sub_string=raw_input()
    start=0
    answer=0
    length=len(string)
    index=string.find(sub_string,start,length)
    while index<>-1:
        start=index+1
        answer=answer+1
        index=string.find(sub_string,start,length)
    print answer
    
    0 讨论(0)
  • 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')
    
    0 讨论(0)
  • 2020-11-22 14:33
    #counting occurence of a substring in another string (overlapping/non overlapping)
    s = input('enter the main string: ')# e.g. 'bobazcbobobegbobobgbobobhaklpbobawanbobobobob'
    p=input('enter the substring: ')# e.g. 'bob'
    
    counter=0
    c=0
    
    for i in range(len(s)-len(p)+1):
        for j in range(len(p)):
            if s[i+j]==p[j]:
                if c<len(p):
                    c=c+1
                    if c==len(p):
                        counter+=1
                        c=0
                        break
                    continue
            else:
                break
    print('number of occurences of the substring in the main string is: ',counter)
    
    0 讨论(0)
  • 2020-11-22 14:34

    string.count(substring), like in:

    >>> "abcdabcva".count("ab")
    2
    

    Update:

    As pointed up in the comments, this is the way to do it for non overlapping occurrences. If you need to count overlapping occurrences, you'd better check the answers at: "Python regex find all overlapping matches?", or just check my other answer below.

    0 讨论(0)
  • 2020-11-22 14:34

    This makes a list of all the occurrences (also overlapping) in the string and counts them

    def num_occ(str1, str2):
        l1, l2 = len(str1), len(str2)
        return len([str1[i:i + l2] for i in range(l1 - l2 + 1) if str1[i:i + l2] == str2])
    

    Example:

    str1 ='abcabcd'
    str2 = 'bc'
    

    will create this list but save only the BOLD values:

    [ab, bc, ca, ab, bc, cd]

    that will return:

    len([bc, bc])
    
    0 讨论(0)
  • 2020-11-22 14:35

    For overlapping count we can use use:

    def count_substring(string, sub_string):
        count=0
        beg=0
        while(string.find(sub_string,beg)!=-1) :
            count=count+1
            beg=string.find(sub_string,beg)
            beg=beg+1
        return count
    

    For non-overlapping case we can use count() function:

    string.count(sub_string)
    
    0 讨论(0)
提交回复
热议问题