La chaîne Python commence avec ()

La méthode startswith () renvoie True si une chaîne commence par le préfixe spécifié (chaîne). Sinon, il renvoie False.

La syntaxe de startswith()est:

 str.startswith (préfixe (, début (, fin)))

Paramètres beginwith ()

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

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

Valeur de retour de startswith ()

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

  • Il renvoie True si la chaîne commence par le préfixe spécifié.
  • Il renvoie False si la chaîne ne commence pas par le préfixe spécifié.

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

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

Production

 Faux Vrai Vrai

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

 text = "Python programming is easy." # start 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)

Production

 Vrai Faux Vrai

Passer Tuple à startswith ()

Il est possible de passer un tuple de préfixes à la startswith()méthode en Python.

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

Exemple 3: startswith () Avec Tuple Prefix

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

Production

 Vrai Faux Faux

Si vous avez besoin de vérifier si une chaîne se termine par le suffixe spécifié, vous pouvez utiliser la méthode endswith () en Python.

Articles intéressants...