Sub topic 5
Testing how a string starts or ends
This chapter assumes you know basic Python syntax, string literals and indexing, tuples, and simple if statements and for loops. You should also know from the earlier chapters that string methods return new values and never change the original string.
What startswith and endswith do
str.startswith(prefix) and str.endswith(suffix) answer one yes/no question each. Does the string begin with this text? Does it end with this text? Both return a bool, and both compare case-sensitively.
name = "report.csv"
print(name.startswith("rep")) # True
print(name.endswith(".csv")) # True
print(name.endswith(".CSV")) # False
print(name.startswith("port")) # FalseThe check covers the whole prefix or suffix. If the argument is longer than the string, the result is False rather than an error:
print("abc".startswith("abcd")) # False
print("abc".endswith("xabc")) # FalseWhy not just slice?
You could write s[:len(p)] == p. That works, but it builds a temporary string and makes you manage the length yourself. A second reason is that indexing fails on empty input, and the methods do not:
line = ""
print(line.startswith("#")) # False
try:
print(line[0] == "#")
except IndexError:
print("IndexError on empty string")Use line.startswith("#") for a comment check. line[0] == "#" crashes on blank lines.
Several alternatives at once
Both methods accept a tuple of strings and return True if any item matches. This replaces a chain of or conditions.
files = ["a.py", "b.txt", "c.PY", "d.md"]
wanted = [f for f in files if f.endswith((".py", ".md"))]
print(wanted) # ['a.py', 'd.md']The argument must be a tuple. A list, set, or other iterable raises TypeError:
try:
"a.py".endswith([".py", ".md"])
except TypeError as exc:
print(type(exc).__name__) # TypeErrorIf your alternatives live in a list or set, convert them with tuple(...) first.
extensions = [".py", ".md"]
print("notes.md".endswith(tuple(extensions))) # TrueFinding out which alternative matched
The methods only say whether something matched. When you need to know which item matched, loop over the candidates yourself. next with a default is a compact way to do it:
schemes = ("https://", "http://", "ftp://")
url = "https://example.com"
matched = next((p for p in schemes if url.startswith(p)), None)
print(matched) # https://If candidates overlap, put the longest one first. Here "http://" is not a prefix of "https://", so the order is safe. With candidates such as "ab" and "abc" it would not be.
Restricting the check with start and end
Both methods take optional start and end positions, which work like slice bounds. The test then applies to s[start:end] without creating that slice.
s = "data_2026.csv"
print(s.startswith("2026", 5)) # True (checks from index 5)
print(s.startswith("data", 0, 4)) # True
print(s.endswith("data", 0, 4)) # True (the region ends at index 4)
print(s.endswith(".csv", 0, -1)) # False (the region drops the last char)Two details are easy to forget:
- For
endswith,endmarks where the region stops, sos.endswith("data", 0, 4)tests whethers[0:4]ends with"data". - Negative values count from the end of the string, as in slicing.
With a tuple argument, the same start and end apply to every item.
Empty strings and empty tuples
An empty string is a prefix and a suffix of every string, including the empty one. An empty tuple matches nothing.
print("abc".startswith("")) # True
print("".endswith("")) # True
print("abc".startswith(())) # FalseThis matters when the prefix comes from data. If a config value turns out to be "", startswith quietly returns True for every input. Check for an empty prefix first if that would be a bug in your program.
Case sensitivity
Neither method has a case-insensitive mode. Normalize the string first, then test:
filename = "README.MD"
print(filename.endswith(".md")) # False
print(filename.lower().endswith(".md")) # TrueFor plain ASCII names, lower() is enough. For text where case rules are more complicated, such as German ß, use casefold(), which a later chapter covers. Normalize the test text only. Keep the original string if you need to preserve its capitalization afterward.
Exact-text matching, not patterns
The argument is literal text. Characters such as *, ., and ? have no special meaning:
print("report.csv".endswith("*.csv")) # False
print("report.csv".endswith(".csv")) # TrueThe literal text can still match more than you intended. A suffix without its dot also matches names that merely end in those letters:
print("mycsv".endswith("csv")) # True (probably not what you wanted)
print("mycsv".endswith(".csv")) # FalseInclude the delimiter (., /, _) in the test when it is part of what you mean.
Multi-part extensions
endswith handles multi-dot suffixes directly. This is where it beats os.path.splitext, which only returns the last piece.
archive = "backup.tar.gz"
print(archive.endswith(".gz")) # True
print(archive.endswith(".tar.gz")) # True
from pathlib import Path
print(Path(archive).suffix) # .gz
print(Path(archive).suffixes) # ['.tar', '.gz']For real file paths, pathlib is usually the better tool for extracting parts. Use endswith for a quick yes/no test on a name.
From a test to an edit
A prefix or suffix test is often the first half of a two-step edit. You check, then you cut. The slicing version looks like this:
def strip_scheme(url):
for p in ("https://", "http://"):
if url.startswith(p):
return url[len(p):]
return url
print(strip_scheme("https://example.com")) # example.com
print(strip_scheme("example.com")) # example.comWhen you only need one prefix or suffix, removeprefix and removesuffix (Python 3.9+) do the test and the cut in one call. They return the string unchanged if the text is absent.
print("https://example.com".removeprefix("https://")) # example.com
print("example.com".removeprefix("https://")) # example.comThey accept only a single string, not a tuple. When you have several candidates, keep the loop above.
A complete example: classifying log lines
This script combines the ideas so far: a blank-safe comment check, a tuple of prefixes, and normalization before testing.
def classify(line):
line = line.strip()
if not line or line.startswith("#"):
return "skip"
if line.upper().startswith(("ERROR", "FATAL")):
return "problem"
return "normal"
lines = [
"# nightly job",
"",
"INFO started",
"error: disk full",
"FATAL: out of memory",
" info: done ",
]
for text in lines:
print(f"{classify(text):8} {text!r}")Output:
skip '# nightly job'
skip ''
normal 'INFO started'
problem 'error: disk full'
problem 'FATAL: out of memory'
normal ' info: done 'The strip() call comes first so that leading spaces do not hide a prefix. The original text is never modified, because each method returns a new value.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Passing a list: `s.endswith([".a", ".b"])` | `TypeError` | Pass a tuple: `(".a", ".b")` |
| Forgetting case: `"A.PY".endswith(".py")` | `False` | Normalize first with `lower()` |
| Omitting the dot: `endswith("csv")` | Matches `"mycsv"` too | Include `.csv` |
| Using `strip(".py")` to drop a suffix | Removes any of the characters `.`, `p`, `y` from both ends | Use `removesuffix(".py")` |
| Empty prefix from config | Always `True` | Validate before testing |
| Passing a string where bytes are needed | `TypeError` on `bytes` | Use `b"..."` arguments |
The bytes type has the same two methods, and the argument must also be bytes:
header = b"\x89PNG\r\n"
print(header.startswith(b"\x89PNG")) # TrueWhen to reach for something else
Prefix and suffix tests cover fixed text at the edges of a string. Switch tools when the requirement changes:
- You need the match position, or the text can be anywhere: use
in,find, orindex. - You need a pattern, such as "starts with one or more digits": use
re.match. - You are working with file paths: use
pathlib.
Exercise
Write a function is_image(name) that returns True for file names ending in .png, .jpg, .jpeg, or .gif regardless of capitalization. Then predict the result of is_image("photo.JPG") and is_image("pngfile").
Show answer
def isimage(name):
return name.lower().endswith((".png", ".jpg", ".jpeg", ".gif"))
`isimage("photo.JPG") is True, because lower() turns the name into "photo.jpg" before the test. is_image("pngfile")` is False, because none of the suffixes match: the dot in each suffix is required, and "pngfile" does not end with any of them.
Exercise
What does each expression return? (a) "hello".startswith("") (b) "hello".startswith(()) (c) "hello".endswith("llo", 0, 4) (d) "hello".startswith(["he", "ha"])
Show answer
(a) True, because the empty string is a prefix of every string. (b) False, because an empty tuple contains no candidate to match. (c) False, because the region is "hell", which does not end with "llo". (d) It raises TypeError, because the argument must be a str or a tuple of str, not a list.