search
str.endswith
Returns True if the string ends with the given suffix, otherwise False. suffix may be a tuple of strings to test multiple candidates at once.
str.endswith(suffix[, start[, end]]) Parameters
| Parameter | Purpose |
|---|---|
| suffix | string or tuple of strings to test |
| start | position to start testing |
| end | position to stop testing |
Examples
>>> 'report.pdf'.endswith('.pdf')
True simple suffix match
>>> 'photo.jpg'.endswith(('.jpg', '.jpeg', '.png'))
True tuple tests multiple extensions in one call
>>> 'hello world'.endswith('hello', 0, 5)
True end index narrows the compared slice
>>> 'FILE.PDF'.endswith('.pdf')
False case-sensitive
Gotcha
Case-sensitive. For file-extension logic, prefer pathlib.PurePath.suffix which handles paths correctly; since 3.9, str.removesuffix() strips a matched tail.
Related methods
str.startswith
Returns True if the string starts with the given prefix, otherwise False. prefix may also be a tuple of strings to test against multiple candidates.
str.rfind
Returns the highest index in the string where substring sub is found within [start:end]. Returns -1 if the substring is not found.
str.rstrip
Returns a copy of the string with trailing characters removed. Defaults to whitespace; a chars argument specifies a set of characters to strip from the right.
str.find
Returns the lowest index in the string where substring sub is found within the slice [start:end]. Returns -1 if the substring is not found, unlike index() which raises ValueError.
str.index
Like find(), but raises ValueError if the substring is not found. Use when the substring is expected to exist and its absence is an error.