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 ])
Code language: CSS (css)
The endswith()
method has three parameters:
suffix
is a string or a tuple of strings to match in thestr
. If thesuffix
is a tuple, the method will returnTrue
if thestr
ends with one of the string element in the tuple. Thesuffix
parameter is mandatory.start
is the position that the method starts searching for thesuffix
. Thestart
parameter is optional.end
is the position in thestr
that the method stops searching for thesuffix
. Theend
parameter 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)
Code language: PHP (php)
Output:
True
Code language: PHP (php)
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)
Code language: PHP (php)
Output:
False
Code language: PHP (php)
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)
Code language: PHP (php)
Output:
True
Code language: PHP (php)
Summary #
- Use the Python string
endswith()
method to determine if a string ends with another string.