Python String endswith() Method Tutorial

Python provides the endswith() method for the string type in order to check if the specified string ends with the specified characters. This can be useful to match specific ends for strings.

endswith() Method Syntax

The endswith() method has the following syntax.

STRING.endswith(CHARS,START,END)
  • STRING is a string variable of value.
  • CHARS is single or more characters to check if the STRING ends with. This is required.
  • START is the start index to check CHARS. This is optional.
  • END is the end index to check CHARS. This is optional.

The return value for the endswith() method is True or False boolean values. If the specified STRING ends with the specified CHARS the return value is True if not False.

Check String Ends With Specified Characters

The most popular and basic usage for the endswith() method is specifying the characters we want to check for the specified string. In the following example we will check is the string variable named name ends with the “il”.

name="ismail"

print(name.endswith("il"))

result=name.endswith("l")
print(result)

print(name.endswith("ma"))

The output is like below.

True
True
False

Check String Ends With Specified Characters After Specified Index

The endswith() method can be also used to check if the specified characters exist after specified index of the given string. The start index number should be specified to check given chars. Also the given chars may or may not located at the end of the given string.

name="ismail"

print(name.endswith("il",2))

print(name.endswith("s",3))

The output is like below.

True
False

Check String Ends With One Of The Specified Characters

The endswith() method provides the ability to match one of the specified multiple characters or character sets. The python tuple can be used to specify multiple items where all of them can be checked against the string. If one of them matches the endswith() method returns True.

name="ismail"


chars = ("i","j","k")

print(name.endswith(chars))

print(name.endswith(("e","d","f")))

The output is like below.

True
False

Leave a Comment