What is the String count() method in Python?

The count() method for the String class in Python is a built-in function that returns the number of times a given substring occurs in a given string.

Syntax

string_name.count(substring, start, end)

Parameters

  • substring: This is a required parameter and the string whose count is to be determined.
  • start: An optional integral parameter that specifies the position to start the search. The default value is 0.
  • end: An optional integral parameter that specifies the position to end the search. The default is the end of the string.

Return value

The count() method returns an integer indicating the number of times a substring appears in a given string.

Code

The following code shows how to use the count() method in Python.

Example 1

Let’s implement the count() method without start and end parameters.

# Python program to demonstrate the
# count() method without start and end parameters
# The string in which occurrence will be checked
string = "Educative.io platform"
# string whose count is to be found
substring ="i"
# counts the number of times substring occurs in
# the given string and returns an integer
print(string.count(substring))

In this case, the substring "i" occurs twice in the whole string, so it returned as such.

Example 2

Let’s implement the count() method with start and end parameters specified.

# Python program to demonstrate the
# count() method with start and end parameters
# The string in which occurrence will be checked
string = "Educative.io platform"
# The string whose count is to be found
substring ="i"
# counts the number of times substring occurs in
# the given string between index 0 and 12 and returns
# an integer
print(string.count(substring, 0, 12))
# counts the number of times substring occurs in
# the given string between index 0 and 12 and returns
# an integer
print(string.count(substring, 0, 9))

In the second instance, since only the characters until index 9 are considered, the second "i" is not counted.

Free Resources