What is the string endswith() method in Python?

String endswith() method

The endswith() method checks for a given suffix in a string.

The Python String endswith() method returns True if a string ends with the specified suffix, and returns False otherwise.

Below is a visual representation of the endswith() method.

Visual illustration of endswith() method

Syntax


string_name.endswith(suffix, start, end)

string_name is the name of the string.


Parameter

  • suffix: Required. This is the string to check.

  • start: Optional. An integer to indicate where the search should begin.

  • end: Optional. An integer to indicate where the search should terminate.

Return type

The endswith() method returns True if a string ends with the specified suffix, and returns False otherwise.

Code

The following code shows how to use the endswith() method in Python:

Example 1

Using the endswith() method without start and end arguments.

# Python code that demonstrate
# .endswith() method
word = "California"
suffix = 'nia'
print (word.endswith(suffix))
result = word.endswith('for')
print (result)
result = word.endswith('nia.')
print (result)

If no start and end indexes are specified, the starting and ending indexes are set to 00 and length 1-1 by default.

Example 2

Using the endswith() method with start and end arguments.

# Python code to demonstrate
# .endswith() method
platform = "Educative.io"
shot = "String endswith() method in python"
# start arguement: 8 and start: 17, end: 34 - 1
if platform.endswith('io', 8) and shot.endswith('python',17, 34):
print ('This shot is available on Educative platform')
else:
print("shot not found")

Free Resources