str.endswith()
Returns True when a string ends with the text you give, or with any one of several endings passed as a tuple.
str.endswith(suffix[, start[, end]])endswith() checks the end of a string and returns True or False. It is the mirror of str.startswith().
The classic use is file extensions: name.endswith(".csv"). Pass a tuple to accept several endings at once, such as (".jpg", ".png").
The check is case-sensitive, so "PHOTO.JPG".endswith(".jpg") is False. Lower-case the name first when case should not matter.
Parameters
| Parameter | What it is |
|---|---|
suffixrequired | The text the string should end with, or a tuple of several texts. |
startoptional, default 0 | Only look at the string from this position. |
endoptional, default len(str) | Treat the string as ending at this position. |
Return value
True if the string ends with suffix (or one of the tuple's items), otherwise False.
Examples
1Check a file extension
name = "sales.csv"
print(name.endswith(".csv"))
print(name.endswith(".xlsx"))True False
2Pick out images
files = ["cat.jpg", "notes.txt", "map.PNG", "logo.png"]
images = [f for f in files if f.lower().endswith((".jpg", ".png"))]
print(images)['cat.jpg', 'map.PNG', 'logo.png']
lower() makes map.PNG match too.
3Check that a sentence ends properly
for s in ["Hello.", "Really?", "Wait"]:
if s.endswith((".", "!", "?")):
print(s, "- ok")
else:
print(s, "- missing punctuation")Hello. - ok Really? - ok Wait - missing punctuation
4Check part of a string with end
code = "ABC-123-X"
print(code.endswith("123", 0, 7))True
With end=7 the check treats the string as "ABC-123".
Common mistakes
Forgetting the dot in an extension
endswith("csv") also matches names like "mycsv". Include the dot.
names = ["data.csv", "notes_csv"]
for n in names:
print(n, n.endswith("csv"), n.endswith(".csv"))data.csv True True notes_csv True False
Questions people ask
How do I check several extensions?
Pass a tuple: name.endswith((".jpg", ".jpeg", ".png")).
How do I remove the ending after checking it?
Use str.removesuffix(), which only removes the ending when it is there.
Is there a better way for file paths?
For real paths, pathlib.Path(name).suffix gives the extension, for example ".csv".