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