How do I check if a string ends with a specific substring in Python?
Antek N
antek n profile pic

In Python, you can check if a string ends with a specific substring using different methods. Here's a detailed explanation of a few commonly used approaches: Using the endswith() method: Theendswith() method is a built-in string method that can be used to check if a string ends with a specified suffix. It returnsTrue if the string ends with the given suffix, andFalse otherwise.

1
2
3
4
5
6
7

my_string = "Hello, World!"

if my_string.endswith("World!"):
    print("The string ends with 'World!'.")
else:
    print("The string does not end with 'World!'.")

In this example,my_string.endswith("World!") checks if the string"Hello, World!" ends with the substring"World!". If it does, the corresponding message is printed. You can also specify a tuple of suffixes to check if the string ends with any of the given suffixes. For example:

1
2

my_string =