Python String endswith() Method

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

  1. suffix(required): This is part of the string for which we are checking if the string is ending with that part.
  2. start(optional):  The suffix starts from here.
  3. end(optional): The suffix ends here.

Return value

It returns a boolean value:

  1. It returns True if a string ends with the specified suffix.
  2. It returns False if a string doesn’t end with the specified suffix.

Visual RepresentationVisual Representation of Python String endswith() Method

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 parametersVisual Representation of Python String endswith() Method (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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.