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 de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Utilisation et exemple de startswith() pour les chaînes de caractères Python

Python string methods

Si la chaîne de caractères commence par le préfixe spécifié (chaîne de caractères), la méthode startswith() retourne True. Sinon, elle retourne False.

La syntaxe de startswith() est :

str.startswith(prefix[, start[, end]])

Paramètres de startswith()

La méthode startswith() utilise au maximum trois paramètres :

  • prefix -Chaîne de caractères ou tuple de chaînes à vérifier

  • start(optionnel)-  doit être vérifié dans la chaîne de caractèresPréfixe dePosition de début.

  • end (optionnel)-  doit être vérifié dans la chaîne de caractèresPréfixe dePosition de fin.

Retour de startswith()

La méthode startswith() retourne une valeur booléenne.

  • Si la chaîne de caractères commence par le préfixe spécifié, retourne True.

  • Si la chaîne de caractères ne commence pas par le préfixe spécifié, retourne False.

Example1:startswith() n'a pas de paramètres start et end

text = "Python est facile à apprendre."
result = text.startswith('est facile')
# Retourne False
print(result)
result = text.startswith('Python est ')
# Returns True
print(result)
result = text.startswith('Python est facile à apprendre.')
# Returns True
print(result)

When running the program, the output is:

False
True
True

Example2:startswith() with start and end parameters

text = "Python programming is easy."
# Starting parameter: 7
# 'programming is easy.' string is searched
result = text.startswith('programming is', 7)
print(result)
# start: 7, end: 18
# 'programming' string is searched
result = text.startswith('programming is', 7, 18)
print(result)
result = text.startswith('program', 7, 18)
print(result)

When running the program, the output is:

True
False
True

Pass a tuple to startswith()

In Python, you can pass a tuple of prefixes to the startswith() method.

If a string starts with any item of a tuple, startswith() returns True. If not, it returns False

Example3:startswith() with tuple prefix

text = "programming is easy"
result = text.startswith(('python', 'programming'))
# Output True
print(result)
result = text.startswith(('is', 'easy', 'java'))
# Output False
print(result)
# With start and end parameters
# 'is easy' string is checked
result = text.startswith(('programming', 'easy'), 12, 19)
# Output False
print(result)

When running the program, the output is:

True
False
False

If you need to check if a string ends with a specified suffix, you canin PythonUseendswith() method.

Python string methods