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()

endswith() Syntax

The syntax of endswith() method is:

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

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

endswith() 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() 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() 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

Get notified of the best deals on our WordPress themes.

You May Also Like
List of Python free ebooks

List of Free Python Books

Table of Contents Hide Python SuccinctlyPython Data Science HandbookThink Python 2nd EditionAutomate the Boring Stuff with PythonMaking Games with Python & PygameData Structures and Algorithms in Python Google Python Style GuideA…
View Post