Tutorial Study Image

Python count()

The count() function in python helps to return the number of occurrences of a given substring in the given string. The method allows specifying the starting and ending of the search in the string.


string.count(substring, start=..., end=...) #Where start(index) is starts from 0
 

count() Parameters:

The count() function takes three parameters in these two is optional.

Parameter Description Required / Optional
substring a string whose count is to be found Required
start  starting index within the string where the search starts Optional
end ending index within the string where the search ends Optional

count() Return Value

The return value should be an integer showing how many times the substring appears in the given string.

Input Return Value
string integer(count)

Examples of count() method in Python

Example 1: How to count number of occurrences of a given substring?


# define string
string = "I love oranges, orange are my favorite fruit"
substring = "orange"

count = string.count(substring)

# print count
print("The count of orange is:", count)
 

Output:


The count of orange is: 2

Example 2: How to count number of occurrences of a given substring using start and end?


# define string
string = "I love oranges, orange are my favorite fruit"
substring = "orange"

count = string.count(substring,6,15)

# print count
print("The count of orange is:", count)
 

Output:


The count of orange is:1