In this article we will discuss different ways to count occurrences of a sub-string in another string and also their index positions.

Count occurrences of a sub-string in another string using string.count()

Python’s String class contains a method to count the non overlapping occurrences of a sub-string in the string object i.e.

It looks for the sub-string s in range start to end and returns it’s occurrence count. If start & end is not provided then it will look in complete string and returns the occurrence count of sub-string  in the string. For example,

Output:

As ‘sample’ string exists at 2 places in the another string, so it returned 2.

Using Python Regex : Count occurrences of a sub string in string

We can easily get the occurrence count using python regex too. For that we will create a regex pattern with sub-string and then find all matches of that regex pattern in another string i.e.

As ‘sample’ string exists at 2 places in the another string, so regex pattern is matched at 2 places and a list of those matches is returned. Length of the list returned will tell the total occurrence count of sub-string in main string.

Count Overlapping occurrences of a sub-string in another string

The ways we have seen till now are not able to count the overlapping sub-strings. Let’s understand by example,

Suppose we have a string which has overlapping occurrence of sub-string ‘that’ i.e.,

Now if we count the occurrence of a sub-string ‘that’ in this string using string.count(),

string.count() will return 2, where as there are 3 overlapping occurrence of ‘that’ in main string.

As, string.count() can not find the overlapping occurrences of a sub-string.  So, let’s create a function to do this,

Now let’s use this function of find occurrence count of a overlapping sub-string ‘that’ in the main string,

Output:

Find occurrence count and index positions of a sub-string in another string

Find indices of non-overlapping sub-string in string using Python regex finditer()

Using Regex find all the matches of a sub-string in another main string and iterate over all those matches to find their index positions i.e.

Output:

It returns the count & indices of non-overlapping sub-strings only. To find the occurrence count & indices of overlapping sub-strings let’s modify the above create function

Find indices of overlapping sub-string in string using Python

Let’s use this function to find indices of overlapping sub-strings in main string,

Output:

Find nth occurrence of a sub-string in another string

Let’s use the same function frequencyCountAndPositions()  to find the nth occurrence of a sub-string in another string i.e.

Output:

Complete example is as follows,

Output:

 

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,