O método endswith () retorna True se uma string termina com o sufixo especificado. Caso contrário, retorna False.
A sintaxe de endswith()
é:
str.endswith (sufixo (, início (, fim)))
Parâmetros endswith ()
O endswith()
leva três parâmetros:
- sufixo - string ou tupla de sufixos a serem verificados
- start (opcional) - Posição inicial onde o sufixo deve ser verificado dentro da string.
- end (opcional) - posição final onde o sufixo deve ser verificado dentro da string.
Valor de retorno de endswith ()
O endswith()
método retorna um booleano.
- Ele retorna True se as strings terminam com o sufixo especificado.
- Ele retorna False se a string não terminar com o sufixo especificado.
Exemplo 1: endswith () Sem parâmetros de início e fim
text = "Python is easy to learn." result = text.endswith('to learn') # returns False print(result) result = text.endswith('to learn.') # returns True print(result) result = text.endswith('Python is easy to learn.') # returns True print(result)
Resultado
Falso Verdadeiro
Exemplo 2: endswith () Com parâmetros de início e fim
text = "Python programming is easy to learn." # start parameter: 7 # "programming is easy to learn." string is searched result = text.endswith('learn.', 7) print(result) # Both start and end is provided # start: 7, end: 26 # "programming is easy" string is searched result = text.endswith('is', 7, 26) # Returns False print(result) result = text.endswith('easy', 7, 26) # returns True print(result)
Resultado
Verdadeiro Falso Verdadeiro
Passando tupla para endswith ()
É possível passar sufixos de tupla para o endswith()
método em Python.
Se a string terminar com qualquer item da tupla, endswith()
retorna True. Caso contrário, retorna False
Exemplo 3: endswith () com sufixo de tupla
text = "programming is easy" result = text.endswith(('programming', 'python')) # prints False print(result) result = text.endswith(('python', 'easy', 'java')) #prints True print(result) # With start and end parameter # 'programming is' string is checked result = text.endswith(('is', 'an'), 0, 14) # prints True print(result)
Resultado
Falso Verdadeiro
Se você precisa verificar se uma string começa com o prefixo especificado, você pode usar o método startswith () em Python.