Python String count()

Python String count() method

Python String count() method is used to count the number of occurrences of a specified value in the given string.

Consider that given string is in x.

x = "Hello World! Hello User!"

Then the return value of x.count(“Hello”) is

2

Because, there are two occurrences of given value "Hello" in the given string.

Syntax of count() method

The syntax of String count() method in Python is given below.

string.count(value, start, end)

The count() method takes three parameters.

ParameterDescription
value[Mandatory]
A string value.
The value whose number of occurrences in the given string has to be found.
start[Optional]
An integer value.
Specifies the starting index, from where to start the search for specified value in the string.
The default value is 0.
end[Optional] Can be specified only if start is specified.
An integer value.
Specifies the ending index, where to stop the search for specified value in the string.
The default value is end of the string.

count() method returns an integer value representing the number of occurrences of the value in given bounds [start, end] in the given string.

Examples

1. count(value) – Count occurrences of value in given Python string

In the following program, we take a string in variable x, and count the number of occurrences of the value “Hello” using String count() method. We shall store the count() returned value in result variable.

Python Program

x = "Hello World! Hello User!"
result = x.count("Hello")
print(f"Count : {result}")
Run Code Copy

Output

Count : 2

2. count(value, start) – Count occurrences of value in given Python string from a specific start

In the following program, we take a string in variable x, and count the number of occurrences of the value “Hello” in the given string x from a start index of 5 using String count() method.

Python Program

x = "Hello World! Hello User!"
result = x.count("Hello", 5)
print(f"Count : {result}")
Run Code Copy

Output

Count : 1

3. count(value, start, end) – Count occurrences of value in given Python string in specific bounds

In the following program, we take a string in variable x, and count the number of occurrences of the value “Hello” in the given string x from a start index of 5 and end index of 20 using String count() method.

Python Program

x = "Hello World! Hello User!"
result = x.count("Hello", 5, 20)
print(f"Count : {result}")
Run Code Copy

Output

Count : 1

Summary

In this tutorial of Python String Methods, we learned about String count() method, its syntax, and examples.

Related Tutorials

Code copied to clipboard successfully 👍