Python3 count() Method
Description
The count() method counts how many times a character occurs in a string. Optional parameters specify the start and end positions of the search within the string.
Syntax
count() method syntax:
str.count(sub, start= 0,end=len(string))
Parameters
- sub -- the substring to search for
- start -- the position in the string where the search begins. Defaults to the first character, whose index is 0.
- end -- the position in the string where the search ends. The first character has index 0. Defaults to the last position of the string.
Return Value
This method returns the number of times the substring occurs in the string.
Example
The following example demonstrates the count() method:
Example
#!/usr/bin/python3
str
=
"www.runoob.com"
sub
=
'o'
(
"str.count('o') : "
,
str
.
count
(
sub
)
)
sub
=
'run'
(
"str.count('run', 0, 10) : "
,
str
.
count
(
sub
,
0
,
10
)
)
The output of the above example is:
str.count('o') : 3
str.count('run', 0, 10) : 1
Python3 Strings