Python string endswith() method with example

The endswith() method in Python is a built-in string method that checks whether the string ends with the specified suffix. If the string ends with the given suffix, it returns True; otherwise, it returns False.

Syntax for the endswith() method:

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

1. suffix: This could be a string or a tuple of suffixes to be checked.

2. start (optional): Starting index where the suffix is to be checked within the string.

3. end (optional): Ending index where the suffix is to be checked within the string.

The start and end parameters define a substring in which the method will look for the suffix. If they are omitted, the entire string is used.

How to use the endswith() method:

str = "Hello world"
print(str.endswith('world')) # Returns: True
print(str.endswith('Hello')) # Returns: False

Example 1

Basic usage check if the string str ends with the string “Python.”. Since it does, the endswith() method returns True.

str = "Hello, welcome to the world of Python."
result = str.endswith("Python.")
print(result) # Prints: True

Example 2

Checks if str ends with any string in the tuple. In this case, str does end with “.”, “Python“, and “Python.”, so endswith() returns True.

str = "Hello, welcome to the world of Python."
suffixes = (".", "Python", "Python.")
result = str.endswith(suffixes)
print(result) # Prints: True

Example 3

If the slice from index 0 to index 5 (which is the string “Hello”) ends with “Hello”. Since it does, endswith() returns True.

str = "Hello, welcome to the world of Python."
start = 0
end = 5
result = str.endswith("Hello", start, end)
print(result) # Prints: True

Leave a Reply

Your email address will not be published. Required fields are marked *