Python String endswith() Method

Determines whether the string ends with a given suffix

Usage

The endswith() method returns True if the string ends with the specified suffix, otherwise returns False.

You can limit the search by specifying optional arguments start and end.

endswith() also accepts a tuple of suffixes to look for.

Syntax

string.endswith(suffix,start,end)

Python string endswith() method parameters
ParameterConditionDescription
suffixRequiredAny string you want to search
startOptionalAn index specifying where to start the search. Default is 0.
endOptionalAn index specifying where to stop the search. Default is the end of the string.

Basic Examples

Example: Check if the string ends with ‘ABC’

S = 'Bob is a CEO at ABC'
x = S.endswith('ABC')
print(x)	# True

Example: Check if the string ends with a ‘ ? ‘

S = 'Is Bob a CEO?'
x = S.endswith('?')
print(x)	# True

Limit endswith() Search to Substring

To limit the search to the substring, specify the start and end parameters.

Example: Check if the substring (4th to 12th character) ends with ‘CEO’

S = 'Bob is a CEO at ABC'
x = S.endswith('CEO',4,12)
print(x)	# True

Provide Multiple Suffixes to Look for

You can provide multiple suffixes to the method in the form of a tuple.

If the string ends with any item of the tuple, the method returns True, otherwise returns False.

Example: Check if the string ends with one of the items in a tuple

S = 'Bob is a CEO'
suffixes = ('CEO','CFO','COO')
x = S.endswith(suffixes)
print(x)	# True
S = 'Sam is a CFO'
suffixes = ('CEO','CFO','COO')
x = S.endswith(suffixes)
print(x)	# True