In this Python tutorial, we will learn how to get the number of occurrences of a substring in this string using string.count() method.
Python – Number of Occurrences of Substring in a String
To count the number of occurrences of a sub-string in a string, use String.count() method on the main string with sub-string passed as argument.
Syntax
The syntax of string.count() method is
string.count(substring)
Return Value
count() method returns an integer that represents the number of times a specified substring appeared without overlap in this string.
Examples
1. Substring in a string without overlap
In the following example program, we take a string and substring. Then we use count() method to count substring occurrences in the string.
Python Program
#the string
str = 'Hello World. Hello TutorialKart.'
#substring
substr = 'Hello'
#finding number of occurrences of substring in given string
count = str.count(substr)
print("Number of occurrences of substring :", count)
Output
Number of occurrences of substring : 2
The sub-string occurred twice, hence the result 2
.
2. Substring in a string with overlap
Consider a string where there could be a overlap of given sub-string. For example aaa
has overlap of sub-string aa
and if you consider the overlap while counting, the number of occurrences would be twice.
count() method does not consider the overlap. The following example demonstrates the same.
Python Program
#the string
str = 'aaaaaaaa'
#substring
substr = 'aa'
#finding number of occurrences of substring in given string
count = str.count(substr)
print("Number of occurrences of substring :", count)
Output
Number of occurrences of substring : 4
Conclusion
In this Python Tutorial, we learned how to count number of occurrences of a sub-string in given string.