Skip to main content

How to check if a string ends with a certain substring in Python

How to check if a string ends with a certain substring in Python.

Here's a step-by-step tutorial on how to check if a string ends with a certain substring in Python.

  1. Start by defining the main string that you want to check. Let's call it main_string.

  2. Next, define the substring that you want to check if it appears at the end of the main string. Let's call it substring.

  3. To check if the main string ends with the substring, you can use the endswith() method in Python. This method returns True if the main string ends with the specified substring, and False otherwise.

   result = main_string.endswith(substring)
  1. The endswith() method is case-sensitive, meaning it considers the case of the characters in the string. If you want to perform a case-insensitive check, you can convert both the main string and the substring to lowercase (or uppercase) before using the endswith() method.
   result = main_string.lower().endswith(substring.lower())
  1. If you want to check if the main string ends with any one of multiple possible substrings, you can pass a tuple of substrings to the endswith() method.
   substrings = ('substring1', 'substring2', 'substring3')
result = main_string.endswith(substrings)

The endswith() method will return True if the main string ends with any one of the substrings in the tuple.

  1. If you only want to check if the main string ends with any one of multiple possible substrings, regardless of case, you can combine the case-insensitive check and the tuple of substrings.
   substrings = ('substring1', 'substring2', 'substring3')
result = main_string.lower().endswith(tuple(s.lower() for s in substrings))

This will return True if the main string ends with any one of the substrings in the tuple, regardless of case.

That's it! You now know how to check if a string ends with a certain substring in Python. Feel free to use these steps and code examples in your own projects.