W3Basic Logo

Python String count() Method

The str.count() method counts the number of occurrences of a substring in a given string within a specified range. If the start and end arguments are not passed, the substring will be searched in the entire string.

Example:

# Python Count the substring
text = "No code has zero defects"

# finds the total occurence of character e
print("The number of occurrences of e is ", text.count("e"))

# count is case-sensitive and hence it treats 'E' as different
print("The number of occurrences of E is", text.count("E"))

Output

The number of occurrences of e is  4
The number of occurrences of E is 0

Note: The count() method is case-sensitive, so it will treat "e" and "E" as different substrings. To perform a case-insensitive search, you can use the lower() or upper() method to convert the string and the substring to the same case before calling the count() method.


Syntax

The Syntax of the str.count() function is:

str.count(sub, start=0, end=len(str))

Here, str is a string.

Parameters

The str.count() function can take three parameters.

  • sub - This is the substring of which you want to count the occurrences.
  • start (optional) - The starting index of the string where the search should begin. The default value is 0, meaning the search will start at the beginning of the string.
  • end (optional) - The ending index of the string where the search should end. The default value is len(str), meaning the search will continue until the end of the string.

Return Value

The str.count() function returns the number of occurrences of a substring within a string. The count will be of type integer.

Example 1: Count the number of occurrences of a substring in the entire string

# Count the number of occurrences of a single character
str = "Hello, world!"
count = str.count("o")
print(count)  # Output: 2

# Count the number of occurrences of a substring at the beginning of the str
str = "Hello, world!"
count = str.count("He")
print(count)  # Output: 1

# Count the number of occurrences of a substring at the end of the str
str = "Hello, world!"
count = str.count("ld!")
print(count)  # Output: 1

# Count the number of occurrences of a substring that spans multiple lines
str = "Hello,\nworld!"
count = str.count("world")
print(count)  # Output: 1

Output

2
1
1
1

Example 2: Count substring within a specified range

In the following example, we will count the number of occurrences of the substring o within the range [3, 9], which is the portion of the string "lo, world". The result will be 2, because the substring o occurs twice in this range.

# Count the number of occurrences of a substring within a specific range of the string
str = "Hello, world!"
count = str.count("o", 3, 9)
print(count)  # Output: 2

Output

2

Reference: Python Official Docs

© 2023 W3Basic. All rights reserved.

Follow Us: