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.

Syntax

The syntax of count() method is:

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

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.

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

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 start and end 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

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like
Python Slice()

Python slice()

Table of Contents Hide slice() Syntax slice() Parametersslice() Return ValueExample 1: Python slice string Get substring using slice objectExample 2: Get substring using negative indexExample 3: Python slice list or Python slice arrayExample 4: Python…
View Post