Home »
Python
Counting the occurrences of a substring in a string using string.count() in Python
Python string.count() function with example: In this article, we are going to learn with an example about string.count() function, to count occurrences of a substring in string.
Submitted by IncludeHelp, on January 19, 2018
Python - string.count() function
string.count() is an in-built function in Python, it is used to find the occurrences of a substring in a given string. It returns an integer value which is the occurrences of the substring.
Syntax:
string.count(substring, [start_index], [end_index])
Here,
- substring is a part of string whose occurrences is to be found.
- [start_index] is an optional argument; it will be the start index of the string, where search will start.
- [end_index] is an optional argument; it will be the end index of the string, where search will stop.
Return value: function returns total number of occurrences of substring.
Example:
Input string is: "I live in India, India is a great country"
Substring to find : "India"
Start_index: None
End_index: None
Output: 2
Input string is: "I live in India, India is a great country"
Substring to find : "India"
Start_index: 0
End_index: 15
Output: 1
Source code:
# Python code to find occurrences
# of a substring in a string
# defining a string
str1 = "I live in India, India is a great country"
# finding occurrences of 'India'
# in complete string
print(str1.count("India"))
# finding occurrences of 'India'
# from 0 to 15 index
print(str1.count("India",0,15))
# finding occurrences of 'i' (small 'i')
# in complete string
print(str1.count("i"))
Output
2
1
5
ADVERTISEMENT
ADVERTISEMENT