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

Python 基础教程

Python 流程控制

Funções do Python

Tipos de Dados do Python

Python 文件操作

Python 对象和类

Python 日期和时间

Python 高级知识

Python 参考手册

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

Métodos de String do Python

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

endswith()的语法为:

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

endswith()参数

endswith()具有三个参数:

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

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

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

endswith()返回值

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

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

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

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

text = "Python é fácil de aprender."
result = text.endswith('to learn')
# Retorno False
print(result)
result = text.endswith('to learn.')
# Retorno True
print(result)
result = text.endswith('Python é fácil de aprender.')
# Retorno True
print(result)

Quando executar o programa, a saída será:

False
True
True

Exemplo2:具有开始和结束参数的endswith()

text = "Python programming is easy to learn."
# Parâmetro start: 7
# "programming is easy to learn." é a string a ser pesquisada
result = text.endswith('learn.', 7)
print(result)
# Inserir parâmetros start e end ao mesmo tempo
# start: 7, end: 26
# "programming is easy" é a string a ser pesquisada
result = text.endswith('is', 7, 26)
# Retorno False
print(result)
result = text.endswith('easy', 7, 26)
# Retorno True
print(result)

Quando executar o programa, a saída será:

True
False
True

Passar tupla para endswith()

Pode passar uma tupla como valor específico para o método endswith() no Python.

Se a string terminar com qualquer item da tupla, o método endswith() retorna True. Caso contrário, retorna False

Exemplo3:endswith() com tupla

text = "programming is easy"
result = text.endswith(('programming', 'python'))
# Saída False
print(result)
result = text.endswith(('python', 'easy', 'java'))
# Saída True
print(result)
# Com os parâmetros start e end
# A string 'programming is' está sendo verificada
result = text.endswith(('is', 'an'), 0,) 14)
# Saída True
print(result)

Quando executar o programa, a saída será:

False
True
True

Se precisar verificar se uma string começa com um prefixo específico, pode usar no PythonMétodo startswith().

Métodos de String do Python