Python Tutorial Python Advanced Python References Python Libraries

Python String - count() Method



The Python count() method is used to find out number of occurrence of a specified character(s) in the string. This method has two optional parameters which can be used to specify starting point and end point of the search within the string. Default values are start and end of the string.

Syntax

string.count(value, start, end)

Parameters

value Required. value of the element which need to be counted in the list.
start Optional. An integer specifying start position of search. default value is 0.
end Optional. An integer specifying end position of search. default value is end of the string.

Return Value

Returns the number of occurrences of specified character(s) in the given string.

Example: Count() in the whole string

In the example below, count() method is used to count number of occurrence of a specified character(s) in the whole string.

MyString = "This is Python Programming."
print(MyString.count("is"))

The output of the above code will be:

2

Example: Count() in a specified section of the string

In the example below, count() method is used to count number of occurrence of a specified character(s) in the given section of the string.

MyString = "This is Python Programming."
print(MyString.count("is", 10, 25))

The output of the above code will be:

0

❮ Python String Methods