Python String endswith() Method

Short answer
str.endswith(suffix) returns True if the string finishes with suffix and False otherwise. Pass a tuple to test several suffixes, such as file extensions.

The classic job for endswith() is checking a file extension: is this .csv, .png or .txt? It is also useful for URLs, punctuation (does the sentence end with ?) and codes with a fixed ending. It is the counterpart of startswith(), and it returns a plain True or False that fits straight into an if statement.

Quick facts
Syntaxtext.endswith(suffix, start, end)
Parameterssuffix: a string or a tuple of strings; start, end (optional): test text[start:end]
ReturnsTrue or False
Case sensitiveYes
Empty suffixAlways True

How str.endswith() works

Python compares the last characters of the string with the suffix.

Python
name = "photo.jpg"
print(name.endswith(".jpg"))
print(name.endswith("jpg"))
print(name.endswith(".JPG"))

The third line is False because the check is case sensitive.

Checking file extensions with a tuple of suffixes

Pass a tuple to accept several endings. Lower-case the name first so photo.PNG is accepted as well.

Python
name = "Holiday.PNG"
print(name.lower().endswith((".png", ".jpg", ".gif")))

For full path handling, pathlib offers Path.suffix, which is more robust than string tests.

endswith() with start and end

The optional arguments restrict the test to text[start:end]. For example "report.csv.bak".endswith(".csv", 0, 10) checks only the first ten characters. This is rarely needed, but it avoids creating a slice in parsing code.

endswith() compared with other approaches

ToolExampleNotes
endswith()s.endswith(".csv")Clear and handles tuples
Slicings[-4:] == ".csv"Breaks if you miscount the length
os.path.splitextsplitext(s)[1] == ".csv"Understands paths; imports a module
removesuffix()s.removesuffix(".csv")Removes the suffix (Python 3.9+)
rstrip()s.rstrip(".csv")Strips a set of characters, not a suffix, so avoid

Examples you can run

Press Run, then edit the code and run it again.

Pick the CSV files from a list

Combine endswith() with a list comprehension to filter file names.

Pick the CSV files from a list
files = ["sales.csv", "notes.txt", "stock.csv", "logo.png"]
print([f for f in files if f.endswith(".csv")])
Expected output['sales.csv', 'stock.csv']

Accept several image extensions

Lower-casing handles .PNG and .Jpg; a tuple handles the alternatives.

Accept several image extensions
uploads = ["a.PNG", "b.pdf", "c.Jpg", "d.gif"]
for u in uploads:
    ok = u.lower().endswith((".png", ".jpg", ".jpeg"))
    print(u, ok)
Expected outputa.PNG True
b.pdf False
c.Jpg True
d.gif False

Detect questions and trailing newlines

A line read from a file often ends with \n, which hides the real ending until you strip it.

Detect questions and trailing newlines
line = "Is this ready?\n"
print(line.endswith("?"))
print(line.strip().endswith("?"))
Expected outputFalse
True

Remove a known suffix safely

Test first, then slice off exactly the suffix length.

Remove a known suffix safely
name = "data.csv"
if name.endswith(".csv"):
    name = name[:-len(".csv")]
print(name)
Expected outputdata

Common mistakes

Passing a list instead of a tuple

✗ Wrong

print("a.txt".endswith([".txt", ".md"]))
TypeError: endswith first arg must be str or a tuple of str, not list

✓ Right

print("a.txt".endswith((".txt", ".md")))

Use a tuple of suffixes.

Forgetting the trailing newline

✗ Wrong

print("data.csv\n".endswith(".csv"))
Prints False

✓ Right

print("data.csv\n".strip().endswith(".csv"))

Call strip() or rstrip() before testing text read from a file.

Using rstrip() to remove a suffix

✗ Wrong

print("mosaic.csv".rstrip(".csv"))
Prints `mosai`, because `rstrip()` removes any of the characters `.`, `c`, `s`, `v`.

✓ Right

print("mosaic.csv".removesuffix(".csv"))

Use removesuffix() (Python 3.9+) or slice after an endswith() test.

Python String endswith() Method: questions people ask

How do I check a file extension in Python?

Use name.lower().endswith(".csv"), or endswith((".csv", ".txt")) for several. For real paths, pathlib.Path(name).suffix also works.

Can endswith() take multiple suffixes?

Yes, but they must be in a tuple, for example s.endswith(("a", "b")).

What is the difference between endswith() and in?

endswith() only looks at the end of the string, while in checks whether the text appears anywhere.

Keep learning

Step-by-step lessons:
Python StringsPython String MethodsPython File Handling

Related:
Python String startswith() MethodPython String strip() MethodPython String lower() MethodPython pathlib

More in string methods:
Python String split() MethodPython String join() MethodPython String strip() MethodPython String lstrip() MethodPython String rstrip() MethodPython String replace() MethodPython String upper() MethodPython String lower() Method See all →