Python string endswith() method returns True if a string ends with the specified suffix. If not, False otherwise.
Syntax
string.endswith(suffix, start, end)
Parameters
- suffix(required): This is part of the string for which we are checking if the string is ending with that part.
- start(optional): The suffix starts from here.
- end(optional): The suffix ends here.
Return value
It returns a boolean value:
- It returns True if a string ends with the specified suffix.
- It returns False if a string doesn’t end with the specified suffix.
Visual Representation
Example 1: How does the String endswith() Method work?
string = "Hello I am a string and I am ending with end"
result = string.endswith("end")
result1 = string.endswith("END")
print("Comparing it with right suffix so output: ",result)
print("Comparing it with wrong suffix so output: ",result1)
Output
Comparing it with right suffix so output: True
Comparing it with the wrong suffix so output: False
Example 2: Using start and end parameters
string = "Cristiano Ronaldo is a Portuguese professional footballer"
right_suf = "Ronaldo"
wrong_suf = "Portuguese"
print(string.endswith(right_suf, 10, 17))
print(string.endswith(wrong_suf, 22, 30))
Output
True
False
Example 3: endswith() With Tuple Suffix
string = "hey, this is easy"
result = string.endswith(('hey', 'hi'))
print(result)
#Checking against multiple endings using a tuple
result = string.endswith(('ronaldo', 'easy', 'messi'))
print(result)
result = string.endswith(('is', 'an'), 0, 14)
print(result)
Output
False
True
False
Ankit Lathiya is a Master of Computer Application by education and Android and Laravel Developer by profession and one of the authors of this blog. He is also expert in JavaScript and Python development.