Python – La méthode String startswith()
La méthode startswith() renvoie True si la chaîne commence par la valeur spécifiée, sinon False.
Syntaxe:
string.startswith(value, start, end)
Paramètres:
La méthode startswith() prend trois paramètres:
- value(Obligatoire) : La valeur, pour vérifier si la chaîne commence par celle-ci
- start(Optionnel) : Un entier spécifiant à quelle position démarrer la recherche
- end(Optionnel) : Un entier spécifiant à quelle position terminer la recherche
Valeur de retour:
La méthode startswith() renvoie:
- True : Si la chaîne commence par le préfixe spécifié.
- False : Si la chaîne ne commence pas par le préfixe spécifié.
Exemple 1:
Vérifiez si la chaîne commence par « Welcome »:
str = "Welcome to WayToLearnX!" res = str.startswith("Welcome") print(res)
Sortie:
True
Exemple 2:
Vérifiez si la position de 11 à 21 commencent par « Way »:
str = "Welcome to WayToLearnX!" res = str.startswith("Way", 11, 21) print(res)
Sortie:
True