×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python String count() Method

By IncludeHelp Last updated : December 08, 2024

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 1

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

Example 2

# 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.