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. By IncludeHelp Last updated : September 17, 2023

Python string.count() function

The 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])

Parameter(s)

  • 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

The function returns total number of occurrences of substring.

Example

Consider the below example with sample input and output:

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

Python program to count the occurrences of a substring in a string

# 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

The output of the above program is:

2
1
5

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.