Python String count() Function
The String count()
method returns the number of times the substring appears in the string.
You can limit the search by specifying optional arguments for start and end indexes.
Syntax
my_string.count(sub, start, end)
count() Parameters
Python String count()
function 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()
function 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
count = my_str.count(substring)
print(count) # Output: 3
# count after 4th index
count_with_start = my_str.count(substring, 4)
print(count_with_start) # Output: 2
# count between 4th and 6th index
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