Python String count() Method
The count()
method returns the number of occurrences of a specified substring in a string.
Syntax
string.count(substring, start, end)
Parameters
substring
: The substring to count in the string
start
(Optional): The starting index to begin the search. Default is 0
.
end
(Optional): The ending index to stop the search (exclusive). Default is the end of the string.
Return Value
Returns an integer representing the number of non-overlapping occurrences of the substring in the string.
Examples
Basic Usage
text = "Python is awesome, Python is easy to learn"
print(text.count("Python")) # Output: 2
With start
Parameter
You can provide the start
parameter to the count()
method if you want to count the occurrences of the substring from the specific index to the end of the string.
text = "Python is awesome, Python is easy to learn"
print(text.count("Python", 5)) # Output: 1
With start
and end
parameters
You can provide the start
and end
parameters to the count()
method if you want to count the occurrences of a substring within the specific range of the string.
text = "Python is awesome, Python is easy to learn"
print(text.count("is", 0, 10)) # Output: 1
Case-Sensitivity
The count()
method is case-sensitive, meaning it treats uppercase and lowercase letters as distinct characters
text = "Python is awesome"
print(text.count("python")) # Output: 0
In the example, the count()
method searches for the exact lowercase substring "python"
but the string text
contains substring "Python"
with an uppercase "P"
. Since the cases don’t match, the method returns 0
.