Python String endswith()

Filed Under: Python

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:


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.


s = 'I Love Python'

print(s.endswith('Python'))  # True

python string endswith() function example

Let’s look at some examples with the start argument.


s = 'I Love Python'

print(s.endswith('Python', 2))  # True
print(s.endswith('Python', 9))  # False

python string ends with example with start index

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.


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.


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.

python string endswith tuple example

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages