Python string endswith() function is very useful when you want a string ends with some sub strings. In this tutorial, we will write some examples to help you understand and learn to use it.
str.endswith(suffix[, start[, end]])
Parameters
suffix – String or tuple of suffixes to be checked
start (optional, int) – Beginning position where suffix is to be checked within the string.
end (optional, int) – Ending position where suffix is to be checked within the string.
Return Value
True or False
Here are some examples.
suffix is a string
suffix = '.com' str = 'https://www.tutorialexample.com' ends = str.endswith(suffix) print(ends) #True
Is case sensitive?
suffix = '.COM' str = 'https://www.tutorialexample.com' ends = str.endswith(suffix) print(ends) #False
String endswith() is case sensitvie.
If start > len(str)?
suffix = '.com' str = 'https://www.tutorialexample.com' ends = str.endswith(suffix, len(str)+1) print(ends) #False
suffix is a tuple
suffix = ('.com', 'e.com') #1 str = 'https://www.tutorialexample.com' ends = str.endswith(suffix) print(ends) #True suffix = ('.com', 'x.com') #2 ends = str.endswith(suffix) print(ends) #True suffix = ('t.com', 'x.com') #3 ends = str.endswith(suffix) print(ends) #False
From the result, we will find these truth when suffix is a tuple.
- String ends with any element in suffix will return True (#1 and #2).
- Only String ends with none of elements in suffix will return False (#3).