How to check if a string ends with a specific suffix in Python
How to check if a string ends with a specific suffix in Python.
Here's a step-by-step tutorial on how to check if a string ends with a specific suffix in Python:
Step 1: Start by defining the string that you want to check.
string = "Hello World"
Step 2: Define the suffix that you want to check for.
suffix = "World"
Step 3: Use the endswith() method to check if the string ends with the specified suffix. The method returns True if the string ends with the suffix, and False otherwise.
result = string.endswith(suffix)
Step 4: Print the result to see the output.
print(result)
The complete code would look like this:
string = "Hello World"
suffix = "World"
result = string.endswith(suffix)
print(result)
This will output True since the string "Hello World" ends with the suffix "World".
Here are a few more examples to demonstrate the usage of endswith() method with different suffixes:
Example 1: Check if a string ends with a specific word.
string = "This is a sentence"
suffix = "sentence"
result = string.endswith(suffix)
print(result)
Output: True
Example 2: Check if a string ends with a specific character.
string = "Hello World"
suffix = "d"
result = string.endswith(suffix)
print(result)
Output: True
Example 3: Check if a string ends with multiple possible suffixes.
string = "Hello World"
suffixes = ["World", "Python", "Universe"]
result = any(string.endswith(suffix) for suffix in suffixes)
print(result)
Output: True
In this example, any() function is used to check if the string ends with any of the specified suffixes. It returns True if at least one of the suffixes is found at the end of the string.
That's it! You now know how to check if a string ends with a specific suffix in Python using the endswith() method.