Count number of occurrences of a given substring in a string

后端 未结 30 1671
不思量自难忘°
不思量自难忘° 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:45
    import re
    d = [m.start() for m in re.finditer(seaching, string)] 
    print (d)
    

    This finds the number of times sub string found in the string and displays index.

    0 讨论(0)
  • 2020-11-22 14:46
    string="abc"
    mainstr="ncnabckjdjkabcxcxccccxcxcabc"
    count=0
    for i in range(0,len(mainstr)):
        k=0
        while(k<len(string)):
            if(string[k]==mainstr[i+k]):
                k+=1
            else:
                break   
        if(k==len(string)):
            count+=1;   
    print(count)
    
    0 讨论(0)
  • 2020-11-22 14:47

    You can count the frequency using two ways:

    1. Using the count() in str:

      a.count(b)

    2. Or, you can use:

      len(a.split(b))-1

    Where a is the string and b is the substring whose frequency is to be calculated.

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

    I'm not sure if this is something looked at already, but I thought of this as a solution for a word that is 'disposable':

    for i in xrange(len(word)):
    if word[:len(term)] == term:
        count += 1
    word = word[1:]
    
    print count
    

    Where word is the word you are searching in and term is the term you are looking for

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

    The best way to find overlapping sub-string in a given string is to use the python regular expression it will find all the overlapping matching using the regular expression library. Here is how to do it left is the substring and in right you will provide the string to match

    print len(re.findall('(?=aa)','caaaab'))
    3
    
    0 讨论(0)
  • 2020-11-22 14:49

    You could use the startswith method:

    def count_substring(string, sub_string):
        x = 0
        for i in range(len(string)):
            if string[i:].startswith(sub_string):
                x += 1
        return x
    
    0 讨论(0)
提交回复
热议问题