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.

In this tutorial, we will learn the syntax of String.count() method, and how to use it to get the number of occurrences of a substring in this string using this count() method.

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

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.

Example.py

#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)
Try Online

Output

Number of occurrences of substring : 2

The sub-string occurred twice, hence the result 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.

Example.py

#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)
Try Online

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.