Python String endswith() Method
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.
| Syntax | text.endswith(suffix, start, end) |
|---|---|
| Parameters | suffix: a string or a tuple of strings; start, end (optional): test text[start:end] |
| Returns | True or False |
| Case sensitive | Yes |
| Empty suffix | Always True |
How str.endswith() works
Python compares the last characters of the string with the suffix.
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
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
| Tool | Example | Notes |
|---|---|---|
endswith() | s.endswith(".csv") | Clear and handles tuples |
| Slicing | s[-4:] == ".csv" | Breaks if you miscount the length |
os.path.splitext | splitext(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.
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.
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.
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.
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"]))✓ Right
print("a.txt".endswith((".txt", ".md")))Use a tuple of suffixes.
Forgetting the trailing newline
✗ Wrong
print("data.csv\n".endswith(".csv"))✓ 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"))✓ 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 →