Python String count() Method
The count() method is used to count the number of occurrences of a character in a string. The optional arguments are the start and end positions of the string search.
Python String count() Syntax
Syntax of the count() method.
str.count(sub, start= 0,end=len(string))
Python String count() Parameters
Parameter | Description |
---|---|
sub |
The substring to search for |
start |
The position of the string to start searching. The default is the first character, and the index value of the first character is 0. |
end |
The position in the string to end the search. The index of the first character in the string is 0. The default is the last position of the string. |
Python String count() Return Value
This method returns the number of times the substring appears in the string.
Python String count() Example#1
The following example shows an instance of the count() method.
#!/usr/bin/python3
str="www.apidemos.com"
sub='o'
print ("str.count('o') : ", str.count(sub))
sub='run'
print ("str.count('run', 0, 10) : ", str.count(sub,0,10))
Output: