In this tutorial, we will delve into one of Python’s built-in string methods –
endswith(). This method is incredibly useful when you need to check if a specific string ends with a certain substring.
How to Use the endswith() Method
The syntax for the
endswith() method is as follows:
string.endswith(suffix[, start[, end]])
This method takes three parameters:
- suffix: This required parameter can be a string or a tuple of suffixes to be checked.
- start (optional): The slice begins from this index in the string.
- end (optional): The slice stops at this index in the string.
endswith() method returns True if the string ends with the specified suffix and False otherwise.
A Simple Example of Using endswith()
text = "Python is fun." result = text.endswith('fun.') print(result) # Outputs: True
In this example, ‘fun.’ is indeed at the end of our text variable, so our program returns True.
An Advanced Example Using start and end Parameters
text = "Python programming is fun." result = text.endswith('programming', 0, 18) print(result) # Outputs: True
In this case, we’re checking whether ‘programming’ is at the end of our substring that starts at index 0 and ends at index 18. As ‘programming’ is indeed the last word in this substring, our program returns True.
endswith() method is a powerful tool for checking if a string ends with a specific suffix. It’s simple to use and can be customized with start and end parameters to check within specific sections of your strings.
We hope you found this tutorial helpful! Stay tuned for more Python tips and tricks.