String endswith() Method in Python

String endswith() Method

The endswith() method in Python is used to check whether a string ends with a specified suffix. It returns a Boolean value indicating whether the original string ends with the provided suffix or not.Here's the syntax of the endswith() method:

string.endswith(suffix, start, end)

Parameters:

  • suffix: The suffix that you want to check if the original string ends with.
  • start (optional): The index from which the suffix comparison starts. It is an optional parameter, and if not provided, the comparison starts from the beginning of the string.
  • end (optional): The index at which the suffix comparison ends. It is an optional parameter, and if not provided, the comparison goes until the end of the string.

Example:

# Example string
original_string = "Hello, world!"

# Checking if the string ends with the suffix "world!"
result1 = original_string.endswith("world!")

# Checking if the string ends with the suffix "Hello"
result2 = original_string.endswith("Hello")

print("Original String:", original_string)
print("Ends with 'world!':", result1)
print("Ends with 'Hello':", result2)

Output:

Original String: Hello, world!
Ends with 'world!': True
Ends with 'Hello': False

In this example, we used the endswith() method to check whether the original string ends with two different suffixes, "world!" and "Hello". The method returns True for the first case as "Hello, world!" does end with "world!", and False for the second case as "Hello, world!" does not end with "Hello".

You can also use the optional start and end parameters to perform the suffix check within specific portions of the original string if needed.