Contents
Find Number of Occurrences of Substring in 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
Scenario 1: Substring present in string
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)
Run Output
Number of occurrences : 2
Scenario 2: Substring not present in string
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)
Run 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.
Related Tutorials
- Reverse a Number in Python
- Python – Sum of Two Numbers
- How to Get Number of Elements in Pandas DataFrame?
- Python – Largest of Three Numbers
- Python Program to Add Two Numbers
- Numpy sqrt() – Find Square Root of Numbers
- Python – Check if Number is Armstrong
- Python – Smallest of Three Numbers
- Python String – Find the number of overlapping occurrences of a substring
- Python – Sum of First N Natural Numbers