English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
如果字符串以指定的值结尾,则endswith()方法返回True。如果不是,则返回False。
endswith()的语法为:
str.endswith(suffix[, start[, end]])
endswith()具有三个参数:
suffix -要检查的后缀字符串或元组
start(可选)- 在字符串中检查suffix开始位置。
end(可选)- 在字符串中检查suffix结束位置。
endswith()方法返回一个布尔值。
字符串以指定的值结尾,返回True。
如果字符串不以指定的值结尾,则返回False。
text = "Python is easy to learn." result = text.endswith('to learn') # Retour False print(result) result = text.endswith('to learn.') # Retour True print(result) result = text.endswith('Python is easy to learn.') # Retour True print(result)
Lors de l'exécution de ce programme, la sortie est :
False True True
text = "Python programming is easy to learn." # Paramètre start: 7 # "programming is easy to learn." est la chaîne recherchée result = text.endswith('learn.', 7) print(result) # En传入 start et end 参数 # start: 7, end: 26 # "programming is easy" est la chaîne recherchée result = text.endswith('is', 7, 26) # Retour False print(result) result = text.endswith('easy', 7, 26) # Retour True print(result)
Lors de l'exécution de ce programme, la sortie est :
True False True
Vous pouvez passer un tuple en tant que valeur spécifiée à la méthode endswith() en Python.
Si une chaîne se termine par l'un des éléments d'un tuple, endswith() renvoie True. Sinon, il renvoie False
text = "programming is easy" result = text.endswith(('programming', 'python')) # Sortie False print(result) result = text.endswith(('python', 'easy', 'java')) # Sortie True print(result) # Avec les paramètres start et end # La chaîne 'programming is' est vérifiée result = text.endswith(('is', 'an'), 0,) 14) # Sortie True print(result)
Lors de l'exécution de ce programme, la sortie est :
False True True
Si vous devez vérifier si une chaîne commence par un préfixe spécifié, vous pouvez utiliser PythonMéthode startswith().