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)
Parameter | Condition | Description |
suffix | Required | Any string you want to search |
start | Optional | An index specifying where to start the search. Default is 0. |
end | Optional | An index specifying where to stop the search. Default is the end of the string. |
Basic Examples
# Check if the string ends with ‘ABC’
S = 'Bob is a CEO at ABC'
x = S.endswith('ABC')
print(x)
# Prints True
# Check if the string ends with a ‘ ? ‘
S = 'Is Bob a CEO?'
x = S.endswith('?')
print(x)
# Prints True
Limit endswith() Search to Substring
To limit the search to the substring, specify the start and end parameters.
# 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)
# Prints 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.
# 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)
# Prints True
# Check if the string ends with one of the items in a tuple
S = 'Sam is a CFO'
suffixes = ('CEO','CFO','COO')
x = S.endswith(suffixes)
print(x)
# Prints True