Python String endswith()

Python String endswith() method is a built-in function that determines whether the given string ends with a specific sequence of characters. Let’s take a look at syntax and examples of the Python string endswith() method.

Note: If you want to determine whether the given string begins with a specific sequence of characters, then you can use Python String startswith()

Syntax

The syntax of endswith() method is:

str.endswith(suffix[, start[, end]])

Parameter

The endswith() function can take three parameters

  • suffix – string that needs to be checked in the main string
  • start (optional) – Starting position where suffix needs to be checked within the string.
  • end (optional) – Ending position where suffix needs to be checked within the string.

Return Value

The endswith() function returns true if the given suffix is found at the end of the string. Otherwise, it returns false.

Note: The endswith() function is case-sensitive

Example 1: endswith() method without start and end Parameters

text = "Welcome to Python Tutorials"

# endswith is case-sensitive, returns false
print(text.endswith('tutorials'))

# returns true
print(text.endswith('Tutorials'))

# returns true
print(text.endswith('Python Tutorials'))

Output

False
True
True

Example 2: endswith() method with start and end Parameters

text = "Welcome to Python Tutorials"

# returns true
result = text.endswith("Tutorials", 18)
print(result)

# returns false
result = text.endswith("to", 7, 15)
print(result)

# returns true
result = text.endswith("to", 7, 10)
print(result)

Output

True
False
True

Passing Tuple to endswith()

It’s possible to pass a tuple as a suffix to the endswith() method in Python. If the string ends with any item of the tuple, endswith() function returns True. Otherwise, it returns False

text = "Welcome to Python Tutorials"

# returns true
result = text.endswith(('to', 'Python', 'Tutorials'))
print(result)

# returns true
result = text.endswith(('to', 'Python', 'Tutorials'), 18)
print(result)

# returns true
result = text.endswith(('to', 'Python', 'Tutorials'), 7, 10)
print(result)

Output

True
True
True
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like