Python - Find number of occurrences of substring in a string
Find number of occurrences of substring in a string
To find the number of occurrences of a substring in a string in Python, call count() method on the string, and pass the substring as argument.
The syntax to find the number of occurrences of substring search
in string x
is
x.count(search)
The method returns an integer representing the number of occurrences of the given argument in the string.
Examples
1. Find number of occurrences of the search string "apple"
In the following program, we take a string x
, and a search string search
. We find the number of occurrences of search
string in the string x
.
Python Program
x = 'apple is red. some apples are green.'
search = 'apple'
n = x.count(search)
print('Number of occurrences :', n)
Output
Number of occurrences : 2
2. Find number of occurrences of the search string "banana"
In the following program, we take a string x
, and a search string search
such that search string is not present in the string. string.count() method must return zero for the given data.
Python Program
x = 'apple is red. some apples are green.'
search = 'banana'
n = x.count(search)
print('Number of occurrences :', n)
Output
Number of occurrences : 0
Summary
In this tutorial of Python Examples, we learned how to find the number of occurrences of a search string or substring in a given string using string.count() method, with the help of well detailed examples.