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

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations sur les fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Python string count() usage and example

Python string methods

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

In simple terms, the count() method searches for the givenIn the stringThe substring and returns the number of occurrences of the substring within 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 requires only 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 occurrences of a substring in a given string.

Example1: Calculate the occurrence of a given substring

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

When running the program, the output is:

The occurrence count is: 2

Example2: Use start and end to count the occurrence 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 occurrence count is:", count)

When running the program, the output is:

The occurrence count is: 1

Here, the count is incremented when encountering the first "i" (i.e., the7an index position)

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

Python string methods