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.

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
Python List Remove()

Python List remove()

Table of Contents Hide Syntax of List remove() remove() ParametersReturn Value from List remove()Example 1: Remove element from the listExample 2: remove() method when list has duplicate itemsExample 3: Deleting element…
View Post
Python String Encode()

Python String encode()

Table of Contents Hide encode() Syntaxencode() Parameter encode() Return ValueExample 1- Encode the string to Utf-8 EncodingExample 2- UnicodeEncodeError while encoding stringExample 3- Handling Encoding errors with error parameters Python String…
View Post
Python String To Array

How To Convert Python String To Array

Table of Contents Hide Python String to Arraysplit() Syntaxsplit() ParametersExample 1: Split the string using the default argumentsExample 2: Split the string using the specific characterPython String to Array of…
View Post
Python - List Files In A Directory

Python – List Files in a Directory

Table of Contents Hide Method 1: Using os.listdir() methodMethod 2: Using os.walk() methodMethod 3: Using os.scan() methodMethod 4: Using glob module There are several modules available in Python to list…
View Post