English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python string count() usage and examples

Python string methods

The string count() method returns the number of times the specified value appears in the string.

In simple terms, the count() method searches for the givenIn the stringThe substring and returns the number of times the substring appears in it.

It also has optional parameters, start and end, which specify the start and end positions in the string.

The syntax of the count() method is:

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

String count() parameters

The count() method only needs one parameter to execute. However, it also has two optional parameters:

  • substring -The string to be searched for the count.

  • start (optional) -Search the start index of the string to be searched.

  • end (optional) -Search the end index of the string to be searched.

Note: In Python, the index starts from 0, not1.

The return value of the string method count()

The count() method returns the number of times the substring appears in the given string.

Example1: Calculate the number of occurrences of a given substring

# Define string
string = "Python is awesome, isn't it?"
substring = "is"
count = string.count(substring)
# Output count
print("The number of occurrences is:", count)

When running the program, the output is:

The number of occurrences is: 2

Example2: Use start and end to count the number of occurrences of a given substring

# Define string
string = "Python is awesome, isn't it?"
substring = "i"
# Count between the first 'i' and the last 'i'
count = string.count(substring, 8, 25)
# Output count
print("The number of occurrences is:", count)

When running the program, the output is:

The number of occurrences is: 1

Here, the count is incremented when encountering the first 'i' (i.e., the7index position)

And, it starts after the last 'i' (i.e., the25an index position) before ending. That is, searching from the8characters starting at (includesThe8characters) to the25characters (does not includeThe25The number of characters between

Python string methods