Python String endswith() Method

The endswith() method is used when checking whether a substring is equal to the suffix of the string. This method takes a string that will be compared against the suffix of the other string. This method can take two additional arguments. One is the start, and the other is the end. These specify the starting and ending index of the suffix, of which the method will compare the substring.

Syntax:

string.endswith(substr [, start [, end]])

This endswith() method accepts three parameters. 1st parameter is required, and other two are optional

substr(mandatory) A string that will be compared with the suffix of the other string.
start(optional) The position of the character where the string is to be sliced to check for the suffix. The default position is 0.
end(optional)) The character's position where the sliced substring should end. The default position is the end of the string.
Return Value:

The endswith() returns a boolean value representing whether the suffix of the string ends with the given substring.

			

# Python example of the endswith() method.

mytext = "What Matters More Than Your Talents."

result = mytext.endswith("Talents.")

print(result)

				

Output:

True

Since the variable mytext does end with the given substring, the endswith() method returns True.

			

exampleOfString = "Tsukogami"

substring = "ami"

print(exampleOfString.endswith(substring,1,4))
#prints False

				

Output:

False

In the above example code, the exampleOfString does end with the given substring, but since we have passed 1 and 4 as the start and end parameters, respectively, the endswith() method returns False.