English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python string `endswith()` usage and example

Python string methods

If the string ends with the specified value, the `endswith()` method returns True. If not, it returns False.

The syntax of `endswith()` is:

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

The `endswith()` parameters

The `endswith()` function has three parameters:

  • Suffix -The suffix string or tuple to be checked

  • Start(Optional)- Check in the stringSuffixStart position.

  • End(Optional)- Check in the stringSuffixEnd position.

The `endswith()` return value

The `endswith()` method returns a boolean value.

  • Returns True if the string ends with the specified value.

  • Returns False if the string does not end with the specified value.

Example1: The `endswith()` function without start and end parameters

text = "Python is easy to learn."
result = text.endswith('to learn')
# Return False
print(result)
result = text.endswith('to learn.')
# Return True
print(result)
result = text.endswith('Python is easy to learn.')
# Return True
print(result)

When running the program, the output is:

False
True
True

Example2: The `endswith()` function with start and end parameters

text = "Python programming is easy to learn."
# start parameter: 7
# "programming is easy to learn." is the string to be searched
result = text.endswith('learn.', 7)
print(result)
# Pass both start and end parameters
# start: 7, end: 26
# "programming is easy" is the string to be searched
result = text.endswith('is', 7, 26)
# Return False
print(result)
result = text.endswith('easy', 7, 26)
# Return True
print(result)

When running the program, the output is:

True
False
True

Passing a tuple to endswith()

You can pass a tuple as a specified value to the endswith() method in Python.

If a string ends with any item in the tuple, endswith() returns True. If not, it returns False

Example3:With tuple endswith()

text = "programming is easy"
result = text.endswith(('programming', 'python'))
# Output False
print(result)
result = text.endswith(('python', 'easy', 'java'))
# Output True
print(result)
# With start and end parameters
# 'programming is' string is checked
result = text.endswith(('is', 'an'), 0,) 14)
# Output True
print(result)

When running the program, the output is:

False
True
True

If you need to check if a string starts with a specified prefix, you can use it in Pythonstartswith() method.

Python string methods