In this article, we will understand the use of python string endswith() method.

endswith() belongs to string class and returns True if the string on which it is called ends with a specified string and False otherwise.

Syntax of Python string endswith()

Following is the syntax of endswith() method

string.endswith(other string)

It returns True if the string ends with other string.

Python string endswith() parameters

endswith() accepts a string as argument and checks if the string ends with argument string.

endswith() also accepts two optional parameters which are start and end indexes.

If these values are supplied, then endswith() will search for the specified string between those indexes only and return the result.

As per python docs,

S.endswith(suffix[, start[, end]]) -> bool

Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.

Example,

string.endswith(other string, 0, 5)

This will return True, if the string ends with other string but it will only check from 0 till 5th index.

Python string endswith() examples

Below are the examples of python string endswith() method.

str = 'codippa is website'
str.endswith('website')  # True
str.endswith('is website')  # True
str.endswith('codippa')  # False

These examples are obvious where endswith() simply checks if the string ends with the given string.

endswith() examples with parameters

Below are the examples of endswith() that also uses index parameters.

str.endswith('website', 0, 18)  # True
str.endswith('website', 0, 5)  # False
str.endswith('website', 8)  # True
str.endswith('codippa', 0, 5)  # False

First example will check if the string ends with website but between 0 and 18 indexes, which is True.

Second example will check if string ends with website but between indexes 0 and 5, which is False.

Third will search for the string starting index 8 till the end of string.

Last example will search for the string between indexes 0 and 5 but since the string does not end with codippa, the result will be False.

tuple with endswith()

Instead of directly passing a string argument, you can also supply a tuple of string values.

endswith() will check if the string ends with any of the strings present in tuple and return True or False accordingly.

Example,

str = 'codippa is website'
str.endswith(('is', 'the', 'website')) # True