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.
Start by defining the main string that you want to check. Let's call it
main_string
.Next, define the substring that you want to check if it appears at the end of the main string. Let's call it
substring
.To check if the main string ends with the substring, you can use the
endswith()
method in Python. This method returnsTrue
if the main string ends with the specified substring, andFalse
otherwise.
result = main_string.endswith(substring)
- 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 theendswith()
method.
result = main_string.lower().endswith(substring.lower())
- 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.
- 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.