Python count() method
Description
The Python count() method counts the number of times a character or substring appears in a string. The optional parameters specify the start and end positions for the search.
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 shows how to use the count() method:
Example (Python 2.0+)
#!/usr/bin/python
str
=
"
this is string example....wow!!!
"
;
sub
=
"
i
"
;
"
str.count(sub, 4, 40) :
"
,
str
.
count
(
sub
,
4
,
40
)
sub
=
"
wow
"
;
"
str.count(sub) :
"
,
str
.
count
(
sub
)
The output of the above example is:
str.count(sub, 4, 40) : 2
str.count(sub) : 1
Python Strings