Python string endswith() function returns True
if the string ends with the given suffix, otherwise it returns False
.
Python String endswith()
This function syntax is:
1 2 3 |
str.endswith(suffix[, start[, end]]) |
The suffix can be a string or a tuple of string suffixes to look for in the string.
The start is an optional argument to specify the index from where test starts.
The end is an optional argument to specify the index where the test has to stop.
Python string endswith() example
Let’s look at a simple example of python string endswith() function.
1 2 3 4 5 6 |
s="I Love Python" print(s.endswith('Python')) # True <img class="alignnone wp-image-28633 size-full" src="http://all-learning.com/wp-content/uploads/2018/11/Python-String-endswith.png" alt="Python String endswith()" width="1200" height="628" /> |
Let’s look at some examples with the start argument.
1 2 3 4 5 6 7 |
s="I Love Python" print(s.endswith('Python', 2)) # True print(s.endswith('Python', 9)) # False <img class="alignnone wp-image-28634 size-full" src="http://all-learning.com/wp-content/uploads/2018/11/Python-String-endswith-1.png" alt="Python String endswith()" width="1200" height="628" /> |
The start index is 2 for the first print statement, so the test will use the sub-string “ove Python”. That’s why the first output is True.
For the second print statement, the substring is “hon” that doesn’t end with “Python”. Hence the output is False.
Let’s look at some examples with the start and end arguments.
1 2 3 4 5 6 7 |
s="I Love Python" print(s.endswith('hon', 7, len(s))) # True print(s.endswith('Pyt', 0, 10)) # True print(s.endswith('Python', 8)) # False |
For the first print statement, the substring is “Python” i.e. ending with “hon” and hence the output is True.
In the second print statement, the substring is “I Love Pyt” and hence the output is True.
For the third print statement, the substring is “thon” that doesn’t end with “Python”, hence the output is False.
Python string endswith() example with Tuple
Let’s look at some examples with Tuple of strings as the suffix.
1 2 3 4 5 6 |
s="I Love Python" print(s.endswith(('is', 'Python'))) # True print(s.endswith(('Love', 'Python'), 1, 6)) # True |
For the first print statement, string ends with “Python” and hence the output is True.
For the second print statement, string test begins from index position 1 and ends at index position 6 (excluded). So the substring is ” Love” which ends with “Love” and hence the output as True.
Reference: Official Documentation