Count number of occurrences of a substring in a string in Python
In this tutorial, we will learn how to find and count the total number of occurrences of a substring in a string with Python. In many situations, you have come up with this kind of requirements.
We may need to find how many times a word exists in a sentence or in an article with Python programming.
So in this tutorial, we will learn all of these in a simple way. So stay with me till the end to learn the trick.
Now let’s see the coding step by step:
String = 'to be a good programmer you need to work harder'
Here first we are taking the string from where we need to find the number of occurrences of the substring.
print('The Occurrence of to is ',string.count('to')) print('The Occurrence of need is ',string.count('need'))
In Python, we have predefined count() function which can do our job in an easier way. All we need to do is print string.count(‘substring you need to find’), Python count function will count for us.
The Occurrence of to is 2 The Occurrence of need is 1
Here, the substring “to” occurs 2 times and “need” occurs 1 time. So we are successfully able to count occurrences of a substring or word in a string with Python programming.
Python count() is an inbuilt function has one compulsory argument and two optional argument (starting index from where you want to count and ending index up to which you want to count).
count(substring, starting_index, ending_index)
Now let’s see another example. See the code below:
print('The occurrence of to in this case is ',String.count('to',0,10))
And the output will be:
The occurrence of to in this case is 1
So, in this case, we basically limit our range of string, instead of the whole string. Now we want to count substring only between index 0 and index 10.
Also, read: Count the number of spaces in a string in Python
In between index 0 and index 10 “to” is present only one time. So we get the count 1 instead 2 in the above case.
I hope you enjoyed, see this is simple.