Python3 count() Method
Description
The count() method is used to count the number of occurrences of a character in a string. The optional parameters are the start and end positions of the search in the string.
Syntax
The syntax of the count() method is as follows:
str.count(sub, start= 0,end=len(string))
Parameters
- sub -- The substring to search for
- start -- The starting position of the search in the string. The default is the first character, whose index value is 0.
- end -- The ending position of the search in the string. The index of the first character in the string is 0. The default is the last position of the string.
Return Value
This method returns the number of times the substring appears in the string.
Example
The following example demonstrates the count() method:
Example
#!/usr/bin/python3
str="www.example.com"
sub='o'
print ("str.count('o') : ", str.count(sub))
sub='run'
print ("str.count('run', 0, 10) : ", str.count(sub,0,10))
str="www.example.com"
sub='o'
print ("str.count('o') : ", str.count(sub))
sub='run'
print ("str.count('run', 0, 10) : ", str.count(sub,0,10))
The output of the above example is as follows:
str.count('o') : 3
str.count('run', 0, 10) : 1
Other Extensions
Python3 Strings