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

Python 基础教程

Python 流程控制

Fonction en Python

Types de données en Python

Python 文件操作

Python 对象和类

Python 日期和时间

Python 高级知识

Python 参考手册

Python 字符串 endswith() 使用方法及示例

Méthodes de chaîne Python

如果字符串以指定的值结尾,则endswith()方法返回True。如果不是,则返回False。

endswith()的语法为:

str.endswith(suffix[, start[, end]])

endswith()参数

endswith()具有三个参数:

  • suffix -要检查的后缀字符串或元组

  • start(可选)- 在字符串中检查suffix开始位置。

  • end(可选)- 在字符串中检查suffix结束位置。

endswith()返回值

endswith()方法返回一个布尔值。

  • 字符串以指定的值结尾,返回True。

  • 如果字符串不以指定的值结尾,则返回False。

Exemple1:没有开始和结束参数的endswith()

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

Exemple2:带有开始和结束参数的endswith()

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

Passer un tuple à endswith()

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

Exemple3:endswith() avec un tuple

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().

Méthodes de chaîne Python