Signup/Sign In

Python String count()

Python String count() is used in the case if you want the number of occurrences of a substring in a string.

  • Python String count() is an inbuilt function.

  • This method searches the specified substring in the string and returns the number of occurrences of that substring in the given string.

  • This method mainly returns an integer that specifies the count of the occurrence of a substring in a string.

Python String count(): Syntax

Below we have a basic syntax of String count() in Python:

string.count(substring, start, end)

Python String count(): Parameters

Given below is a description of Parameters of count() as there are three parameters:

  • substring:

It is a mandatory parameter used to specify the string whose count is to be found.

  • start:

It is an optional parameter used to specify the starting index of the string from where our search starts.

  • end:

It is an optional parameter used to specify the ending index of the string where the search ends.

Python String count(): Basic Example

Below we have an example to show the working of String count() function:

john = 'What did you bring Mr. Bing'
substring = 'ing'
count = john.count(substring)
print('The substring occurs {} times'.format(count))

In the above example String format is used to format the string; we are searching 'ing' i.e no of time the ing has occurred in the specified string. The output for the same is given below:


The substring occurs 2 times

Example of String count() Using start and end parameter


john= 'What did you bring Mr. Bing'
substring = 'ing'
count = friend.count(substring, 11, 18)
print('The substring occurs {} times'.format(count))

In the above example, we have specified the start and end parameter; the output for the same is given below:


The substring occurs 1 times

Time For Live Example!

Let us see the Live example for string count() which is given below:

Summary

In this tutorial, we have learned count() method of strings in Python that is used for number of occurrences of a substring in a string. We had also seen the basic syntax and parameters of this method with a basic Example.There is also a Live Example for the same.



About the author:
Aspiring Software developer working as a content writer. I like computer related subjects like Computer Networks, Operating system, CAO, Database, and I am also learning Python.