str.endswith()
str.endswith(suffix[, start[, end]]) Returns:
bool · Updated March 13, 2026 · String Methods strings checking suffix
The .endswith() method checks whether a string ends with a specified substring or one of several possible suffixes. It returns a boolean value, making it useful for conditional logic in file handling, validation, and text processing.
Syntax
str.endswith(suffix[, start[, end]])
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
suffix | str or tuple | — | The substring or tuple of substrings to check for at the end of the string |
start | int | 0 | Starting position for the search |
end | int | len(string) | Ending position for the search |
Returns: bool — True if the string ends with the suffix, False otherwise.
Examples
Basic usage
text = "hello.txt"
print(text.endswith(".txt"))
# True
print(text.endswith(".pdf"))
# False
Checking multiple suffixes
filename = "document.pdf"
# Check against multiple extensions
if filename.endswith((".pdf", ".doc", ".docx")):
print("This is a document file")
# This is a document file
This is useful when you need to check a file against multiple allowed extensions.
Using start and end parameters
url = "https://example.com/page"
# Check only the domain portion
print(url.startswith("https", 0, 8))
# True
# Check last 4 characters
print(url.endswith(".com")) # False
The start and end parameters let you check a specific slice of the string without creating a substring first.
Practical file handling example
import os
files = ["report.pdf", "data.csv", "image.png", "script.py", "readme.txt"]
for f in files:
if f.endswith((".pdf", ".txt")):
print(f"Found document: {f}")
# Found document: report.pdf
# Found document: readme.txt
Common Patterns
Validating file extensions
def allowed_file(filename, allowed_extensions):
return any(filename.endswith(ext) for ext in allowed_extensions)
print(allowed_file("photo.jpg", [".jpg", ".png", ".gif"]))
# True
print(allowed_file("photo.exe", [".jpg", ".png", ".gif"]))
# False
Checking string completions
questions = [
"What is Python?",
"How do you install Python?",
"Why use Python?",
"When was Python created?"
]
# Find questions starting with "How" or "What"
for q in questions:
if q.startswith(("How", "What")):
print(f"Question word: {q.split()[0]}")
# Question word: What
# Question word: How
Using with path handling
filepath = "/home/user/documents/report.pdf"
# Check file extension
print(filepath.endswith(".pdf"))
# True
# Check for multiple possible extensions
print(filepath.endswith((".pdf", ".docx", ".xlsx")))
# True
Errors
.endswith() accepts a tuple of suffixes. Passing any other non-string iterable (like a list) raises a TypeError:
# This works - tuple is accepted
"file.txt".endswith(["txt", "pdf"])
# TypeError: endswith first arg must be str or tuple
# Correct usage with tuple
"file.txt".endswith(("txt", "pdf"))
# True