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