learn how to use python string count() with example

The count() method in Python is a built-in function that counts the number of times a substring appears in a string. This method is case-sensitive.

How to use the count() method:

string = "Hello, World!"
substring = "l"
count = string.count(substring)

print("The count is:", count)

Output:

The count is: 3

General syntax for the count() method:

string.count(substring, start=..., end=...)

1. substring is the substring that you are searching for in the string.

2. start and end are optional arguments specifying a range within the string where you want to search for the substring. By default, the search is performed for the whole string.

Example 1

Counting the occurrence of a character.

string = "Hello, World!"
character = "o"
count = string.count(character)
print("The count is:", count)

Output:

The count is: 2

Example 2

Counting the occurrence of a substring.

string = "I love Python. Python is great. Python is easy to learn."
substring = "Python"
count = string.count(substring)
print("The count is:", count)

Output:

The count is: 3

Example 3

Counting the occurrence of a substring within a range.

string = "I love Python. Python is great. Python is easy to learn."
substring = "Python"
start = 0
end = 20
count = string.count(substring, start, end)
print("The count is:", count)

Output:

The count is: 1