Python 3 – String endswith() Method
If you’re working with strings in Python, you may need to check if a specific string ends with a specific suffix. Fortunately, Python provides the endswith() method for strings that help us with this problem.
Syntax
Here is the syntax for the endswitch() method:
string.endswith(suffix, start, end)
Parameters:
– suffix – Required. Defines the suffix that we want to check against.
– start – Optional. Specify the starting position of the search.
– end – Optional. Specify the ending position of the search.
The start and end parameters can be used to specify a range of characters to search through.
Return Value
The method returns True if the string ends with the specified suffix; otherwise, it returns False.
Examples
Let’s take a look at several examples to understand how the endswith() method works.
Example 1 – Basic Usage
string = "Hello, World!"
result = string.endswith("World!")
print(result) # True
In this example, we define a string “Hello, World!” and check if it ends with the suffix “World!”. Since it does, we get the output “True”.
Example 2 – Using start and end Parameters
string = "apple, banana, cherry"
result = string.endswith("banana", 6, 12)
print(result) # True
In this example, we search for the suffix “banana” in the substring from position 6 to position 12. Since the substring ends with the suffix, we get the output “True”.
Example 3 – Multiple Suffixes
string = "To be or not to be, that is the question."
result = string.endswith(("question.", "neither.", "either."))
print(result) # True
In this example, we provide multiple suffixes to the endswith() method as a tuple. The method then checks if the string ends with any of the suffixes. If it does, we get the output “True”.
Conclusion
In conclusion, the endswith() method is a useful Python built-in method for strings that enable us to check if a string ends with a specific suffix. By providing the suffix to be checked, and optionally the start and end range, the method returns True or False. Use the endswith() method whenever you need to perform an end-based string check.