La chaîne Python se termine par ()

La méthode endswith () renvoie True si une chaîne se termine par le suffixe spécifié. Sinon, il renvoie False.

La syntaxe de endswith()est:

 str.endswith (suffixe (, début (, fin)))

Endwith () Paramètres

Le endswith()prend trois paramètres:

  • suffixe - Chaîne ou tuple de suffixes à vérifier
  • start (facultatif) - Position de début où le suffixe doit être vérifié dans la chaîne.
  • end (facultatif) - Position de fin où le suffixe doit être vérifié dans la chaîne.

Valeur de retour de endswith ()

La endswith()méthode renvoie un booléen.

  • Il renvoie True si les chaînes se terminent par le suffixe spécifié.
  • Il retourne False si la chaîne ne se termine pas par le suffixe spécifié.

Exemple 1: endswith () Sans paramètres de début et de fin

 text = "Python is easy to learn." result = text.endswith('to learn') # returns False print(result) result = text.endswith('to learn.') # returns True print(result) result = text.endswith('Python is easy to learn.') # returns True print(result)

Production

 Faux Vrai Vrai

Exemple 2: endswith () Avec les paramètres de début et de fin

 text = "Python programming is easy to learn." # start parameter: 7 # "programming is easy to learn." string is searched result = text.endswith('learn.', 7) print(result) # Both start and end is provided # start: 7, end: 26 # "programming is easy" string is searched result = text.endswith('is', 7, 26) # Returns False print(result) result = text.endswith('easy', 7, 26) # returns True print(result)

Production

 Vrai Faux Vrai

Passer Tuple à endswith ()

Il est possible de passer un suffixe de tuple à la endswith()méthode en Python.

Si la chaîne se termine par un élément du tuple, endswith()renvoie True. Sinon, il renvoie False

Exemple 3: endswith () avec suffixe tuple

 text = "programming is easy" result = text.endswith(('programming', 'python')) # prints False print(result) result = text.endswith(('python', 'easy', 'java')) #prints True print(result) # With start and end parameter # 'programming is' string is checked result = text.endswith(('is', 'an'), 0, 14) # prints True print(result)

Production

 Faux Vrai Vrai

Si vous avez besoin de vérifier si une chaîne commence par le préfixe spécifié, vous pouvez utiliser la méthode startswith () en Python.

Articles intéressants...