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: This is part of the string for which we are checking if the string is ending with that part.
  2. start:  The suffix starts from here; it is optional.
  3. end: The suffix ends here; it is optional.

Return value

The endswith() method 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.

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: How to Use string.endswith() method

string = "This is a string and is awesome"

right_suf = "some"

wrong_suf = "some!"

print(string.endswith(right_suf, 28, 31))
print(string.endswith(wrong_suf, 28, 31))

Output

False

False

Example 3: Python endswith() With Tuple Suffix

text = "hey, this is easy"
result = text.endswith(('hey', 'hi'))

print(result)

result = text.endswith(('python', 'easy', 'java'))

print(result)

result = text.endswith(('is', 'an'), 0, 14)

print(result)

Output

False
True
False

That’s it.

Leave a Comment

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