Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of occurrences of a substring in a string

Tags:

python

string

People also ask

How do you count occurrences of substring in a string in Python?

Python String count() Method Python String count() function is an inbuilt function in python programming language that returns the number of occurrences of a substring in the given string. Parameters: The count() function has one compulsory and two optional parameters.

How many times a substring appears in a string?

Count Number of Occurrences in a String with .count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.


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.


s = 'arunununghhjj'
sb = 'nun'
results = 0
sub_len = len(sb)
for i in range(len(s)):
    if s[i:i+sub_len] == sb:
        results += 1
print results

Depending what you really mean, I propose the following solutions:

  1. You mean a list of space separated sub-strings and want to know what is the sub-string position number among all sub-strings:

    s = 'sub1 sub2 sub3'
    s.split().index('sub2')
    >>> 1
    
  2. You mean the char-position of the sub-string in the string:

    s.find('sub2')
    >>> 5
    
  3. You mean the (non-overlapping) counts of appearance of a su-bstring:

    s.count('sub2')
    >>> 1
    s.count('sub')
    >>> 3
    

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

To find overlapping occurences of a substring in a string in Python 3, this algorithm will do:

def count_substring(string,sub_string):
    l=len(sub_string)
    count=0
    for i in range(len(string)-len(sub_string)+1):
        if(string[i:i+len(sub_string)] == sub_string ):      
            count+=1
    return count  

I myself checked this algorithm and it worked.