String method

str.endswith()

Returns True when a string ends with the text you give, or with any one of several endings passed as a tuple.

BeginnerEvery example below runs in your browser. Change the code and press Run.

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

ParameterWhat it is
suffix
required
The text the string should end with, or a tuple of several texts.
start
optional, default 0
Only look at the string from this position.
end
optional, 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

Pythoneditable
name = "sales.csv"
print(name.endswith(".csv"))
print(name.endswith(".xlsx"))
Output
True
False

2Pick out images

Pythoneditable
files = ["cat.jpg", "notes.txt", "map.PNG", "logo.png"]
images = [f for f in files if f.lower().endswith((".jpg", ".png"))]
print(images)
Output
['cat.jpg', 'map.PNG', 'logo.png']

lower() makes map.PNG match too.

3Check that a sentence ends properly

Pythoneditable
for s in ["Hello.", "Really?", "Wait"]:
    if s.endswith((".", "!", "?")):
        print(s, "- ok")
    else:
        print(s, "- missing punctuation")
Output
Hello. - ok
Really? - ok
Wait - missing punctuation

4Check part of a string with end

Pythoneditable
code = "ABC-123-X"
print(code.endswith("123", 0, 7))
Output
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.

Pythoneditable
names = ["data.csv", "notes_csv"]
for n in names:
    print(n, n.endswith("csv"), n.endswith(".csv"))
Output
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".

Spotted a mistake on this page? Tell us