Skip to main content

Python String endswith() Function

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() function parameters:

ParameterConditionDescription
suffixRequiredAny string you want to search
startOptionalAn index specifying where to start the search. Default value is 0.
endOptionalAn index specifying where to stop the search. Default value is the end of the string.
note

suffix parameter can be a Tuple of suffixes to look for.

endswith() Return Value

Python String endswith() function 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"

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

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

# endswith() between 4th and 6th index
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