Python String count()

Python String count() method is a built-in function that returns the number of occurrences of a substring in the given string.

count() Syntax

The syntax of count() method is:

string.count(substring, start=..., end=...)

count() Parameter

The count() function can take three parameters, of which two are optional.

  • substring – the string that needs to be searched and get the count.
  • start (Optional) – The starting index in the string from which the search needs to begin. Default is 0.
  • end (Optional) – The ending index in the string from which the search ends. Default is the end of the string.

 count() Return Value

The count() function returns an integer that denotes the number of times the substring occurs in a given string.

Example 1: Count the number of occurrences of a given substring without optional arguments

text = "Python is a popular programming language"

# Note: count() is case-sensitive
print("The count is:",text.count("p"))
print("The count is:",text.count("P"))

Output

The count is: 3
The count is: 1

Example 2: Count the number of occurrences of a given substring with optional arguments

In the first print statement, the string is searched from index 15 till the end of the string and in the second print statement, the string is searched from index 1 to index 12.

text = "Python is a popular programming language"

# Note: count() is case-sensitive
print("The count is:", text.count("a", 15))
print("The count is:", text.count("a", 1, 12))

Output

The count is: 4
The count is: 1
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
List of Python free ebooks

List of Free Python Books

Table of Contents Hide Python SuccinctlyPython Data Science HandbookThink Python 2nd EditionAutomate the Boring Stuff with PythonMaking Games with Python & PygameData Structures and Algorithms in Python Google Python Style GuideA…
View Post