Skip to content

Python String endswith() Method

How to use Python's endswith() method to check if a string ends with a specified suffix, including handling tuples and custom start/end indexes."

The String endswith() method checks if a string ends with a specified suffix. It returns True if the string ends with the specified suffix, and False otherwise.

Syntax

my_string.endswith(suffix, start, end)

endswith() Parameters

Python String endswith() method parameters:

Parameter Condition Description
suffix Required Any string you want to search
start Optional An index specifying where to start the search. Default value is 0.
end Optional An index specifying where to stop the search. Default value is the end of the string.

endswith() Return Value

Python String endswith() method returns a boolean:

  • True if a string ends with the specified suffix.
  • False if a string does not end with the specified suffix.

Examples

Example 1: Check if a string ends with a given suffix

For example, let's check if the string ends with est:

my_str = 'Big, Bigger, Biggest'
suffix = 'est'

result = my_str.endswith(suffix)
print(result) # Output: True

output

True

If the suffix does not appear as suffix of the given string, then endswith() method will return False:

my_str = "Big, Bigger, Biggest"
suffix = 'Aaa'

result = my_str.endswith(suffix)
print(result) # Output: False

output

False

Example 2: Check if a string ends with a given suffix with start and end indexes

If you want to limit the search to a substring of the given string, you can specify the start parameter and/or the end parameter.

my_str = 'Big, Bigger, Biggest'
suffix = "est"

result = my_str.endswith(suffix)       
print(result) # Output: True

result = my_str.endswith(suffix, 4)
print(result) # Output: True

result = my_str.endswith(suffix, 4, 6) 
print(result) # Output: False

output

True
True
False

Example 3: Check if a string ends with a Tuple of possible suffixes

You can pass multiple suffixes to the endswith() method in the form of a Tuple. If the string ends with any item of the tuple, the method returns True, otherwise returns False.

my_str = 'Tom is a CEO'
suffixes = ('CFO','CEO','COO')
result = my_str.endswith(suffixes)

print(result) # Output: True

output

True
my_str = 'Tom is a Dev'
suffixes = ('CFO','CEO','COO')
result = my_str.endswith(suffixes)

print(result) # Output: False

output

False

It works also with start and end parameters:

my_str = 'Tom is a CEO and a Dev'
suffixes = ('CFO','CEO','COO')

print(my_str[6:12]) # Output:  a CEO
result = my_str.endswith(suffixes, 5, 12)

print(result) # Output: True

output

 a CEO
True
Navigation