What is string.endswith() in Python?

The endswith() method in Python checks whether a certain string A ends with a string B.

Returns a Boolean Value

Syntax

stringA.endswith(stringB, start, end)

Parameters

  • stringB: The string to be checked for at the end of stringA.

  • start: The index from which the search should start. start is an optional argument. By default, the value is 0.

  • end: The index up to which the search should be done. end is an exclusive and optional argument. By default, the value is the length of stringA.

Example

string_A = "Life ends with death"
string_B = "death"
print ( string_A.endswith(string_B) ) # endswith() call

In the code above, we check if the Life ends with death string ends with the death string. In this case, it is True because the string ends with death.

Example with index parameters

string_A = "Love JavaScript"
string_B = "Java"
print( string_A.endswith(string_B, 7, 11));
Index for the string "Love JavaScript"

In the code above, we check if the Love JavaScript string ends with the Java string. The search should be made between index 7 (included) and 11 (excluded). In this case, endswith() returns False because the string does not end with Java between the specified indexes.

Free Resources