Skip to content

Python String count() Method

How to use Python's String count() method to find the number of occurrences of a substring or character in a string, including optional start and end index parameters.

The String count() method returns the number of times the substring appears in the string.

Syntax

my_string.count(sub, start, end)

count() Parameters

Python String count() method parameters:

Parameter Condition Description
sub Required Any string you want to search for
start Optional An index specifying where to start the search. Default value is 0.
end Optional An index specifying where to stop the search. Default is the end of the string.

count() Return Value

Python String count() method returns an integer representing the number of occurrences of the specified substring in the string.

Examples

Example 1: Count number of occurrences of a given substring

Let's count the number of occurrences of the substring Bi in the given string

my_str = 'Big, Bigger, Biggest'
substring = 'Bi'

count = my_str.count(substring)
print(count) # Output: 3

output

3

If the substring does not appear in the given string, then count() method will return 0:

my_str = "Big, Bigger, Biggest"
substring = 'Aaa'

count = my_str.count(substring)
print(count) # Output: 0

output

0

Example 2: Count number of occurrences of a given substring with start and end indexes

If you want to count occurrences not starting from the beginning, you have to specify the start parameter. Similarly, you can also specify where to stop the counting with end parameter.

my_str = 'Big, Bigger, Biggest'
substring = "Bi"

count = my_str.count(substring)       
print(count) # Output: 3

count_with_start = my_str.count(substring, 4)
print(count_with_start) # Output: 2

count_with_start_end = my_str.count(substring, 4, 6) 
print(count_with_start_end) # Output: 0

output

3
2
0

Example 3: Count occurrence of a character in a given string

You can also count the number of occurrences of a character in a given string:

my_str = 'Big, Bigger, Biggest'
substring = "g"

count = my_str.count(substring)
print(count) # Output: 5

output

5
Navigation