Python String endswith()
Summary: in this tutorial, you’ll learn how to use the Python string endswith() method to check if a string ends with another string.
Introduction to the Python string endswith() method
The endswith() is a string method that returns True if a string ends with another string. Otherwise, it returns False.
The following illustrates the syntax of the endswith() method:
str.endswith(suffix, [,start [,end ])
The endswith() method has three parameters:
suffixis a string or a tuple of strings to match in thestr. If thesuffixis a tuple, the method will returnTrueif thestrends with one of the string element in the tuple. Thesuffixparameter is mandatory.startis the position that the method starts searching for thesuffix. Thestartparameter is optional.endis the position in thestrthat the method stops searching for thesuffix. Theendparameter is also optional.
The endswith() method searches for the suffix case-sensitively.
To determine if a string starts with another string, you use the string startswith() method.
Python string endswith() method examples
Let’s take some examples of using the string endswith() method.
1) Using the Python string endswith() method to determine if a string ends with another string
The following example uses the string endswith() method to determine if a string ends with another string:
s = 'Beautiful is better than ugly'
result = s.endswith('ugly')
print(result)
Output:
True
As mentioned above, the endswith() method matches the string case-sensitively. So the following example returns False:
s = 'Beautiful is better than ugly'
result = s.endswith('UGLY')
print(result)
Output:
False
2) Using the Python string endswith() method with a tuple
The following example uses the endswith() method to check if a sentence ends with a fullstop (.), a question mark (?), or an exclamation mark (!):
marks = ('.', '?', '!')
sentence = 'Hello, how are you?'
result = sentence.endswith(marks)print(result)
Output:
True
Summary
- Use the Python string
endswith()method to determine if a string ends with another string.