str.startswith() / str.endswith() / in
Methods that check whether a string starts or ends with a specific substring. Commonly used for checking file extensions and validating URLs.
Syntax
# Check if a string starts with the given prefix (returns True / False). str.startswith(prefix, start=0, end=len(str)) # Check if a string ends with the given suffix (returns True / False). str.endswith(suffix, start=0, end=len(str)) # Use the in operator to check if a string contains a substring. substring in str substring not in str
Method / Operator List
| Method / Operator | Description |
|---|---|
| str.startswith(prefix, start, end) | Returns True if the string starts with the given prefix. You can pass a tuple to check multiple prefixes at once. |
| str.endswith(suffix, start, end) | Returns True if the string ends with the given suffix. You can pass a tuple to check multiple suffixes at once. |
| sub in str | Returns True if the string contains the substring. The check is case-sensitive. |
| sub not in str | Returns True if the string does not contain the substring. |
Sample Code
# Check the protocol with startswith().
url = "https://example.com/page"
print(url.startswith("https://")) # True
print(url.startswith("http://")) # False
# Check the file extension with endswith().
filename = "report_2026.csv"
print(filename.endswith(".csv")) # True
print(filename.endswith(".xlsx")) # False
# Pass a tuple to check multiple conditions at once.
# More concise than chaining with "or".
image_extensions = (".jpg", ".jpeg", ".png", ".gif", ".webp")
files = ["photo.jpg", "document.pdf", "icon.png", "data.csv"]
image_files = [f for f in files if f.endswith(image_extensions)]
print(image_files) # ['photo.jpg', 'icon.png']
# Example of startswith() with a tuple.
urls = ["https://secure.com", "http://old.com", "ftp://files.com"]
secure = [u for u in urls if u.startswith(("https://", "ftps://"))]
print(secure) # ['https://secure.com']
# Specify a search range.
text = "Python is fun"
print(text.startswith("is", 7)) # True (check from index 7)
print(text.endswith("is", 0, 9)) # True (check within index 0–8)
# Use the in operator to check for substring containment.
sentence = "Python is widely used in data science."
print("data science" in sentence) # True
print("machine learning" in sentence) # False
print("machine learning" not in sentence) # True
# Note that the check is case-sensitive.
print("python" in "Python is great") # False (case mismatch)
print("Python" in "Python is great") # True
# How to check while ignoring case.
text2 = "Hello, World!"
print("world" in text2.lower()) # True (normalize with lower() before checking)
# A practical example that categorizes files by extension.
all_files = [
"index.html", "style.css", "main.js",
"logo.png", "data.json", "script.py"
]
categories = {
"web": (".html", ".css", ".js"),
"image": (".png", ".jpg", ".gif"),
"data": (".json", ".csv", ".xml"),
"python": (".py",),
}
for filename in all_files:
for cat, exts in categories.items():
if filename.endswith(exts):
print(f"{filename} → {cat}")
Notes
Both startswith() and endswith() accept a tuple as an argument to check multiple patterns at once. You cannot pass a list directly. When checking multiple patterns, always use a tuple (wrap values in parentheses or separate them with commas).
The in operator is case-sensitive. If you need a case-insensitive check, normalize the string with lower() or upper() first. For more complex pattern matching with regular expressions, use the re module from the standard library.
Python 3.9 and later added removeprefix() and removesuffix(), which are useful when you want to check for and remove a prefix or suffix in one step. If you need to find the position of a substring, see str.find().
If you find any errors or copyright issues, please contact us.