Sub topic 5
Testing how a string starts or ends
This chapter assumes you know basic Python syntax, how to index strings, how tuples work, and how to read if statements and for loops. You will learn how startswith and endswith work, how to test several alternatives at once, and which mistakes to avoid.
Why not use slicing or `in`?
Suppose you want to know whether a filename ends in .csv. The in operator says only that the text appears somewhere. A slice such as name[-4:] == ".csv" works, but it needs a hard-coded length that you must keep in sync with the suffix. The methods startswith and endswith state your intent directly and return a bool.
name = "report.csv"
print(name.endswith(".csv")) # True
print(name.endswith((".csv", ".tsv"))) # True
print(name.startswith("data")) # FalseBoth methods return a new value and leave the string unchanged, as with every str method.
Testing several alternatives with a tuple
Pass a tuple as the first argument to check several options in one call. The result is True if any element matches. This replaces a chain of or conditions.
name = "report.tsv"
# Chained version
if name.endswith(".csv") or name.endswith(".tsv"):
print("table file")
# Tuple version
if name.endswith((".csv", ".tsv")):
print("table file")Note the double parentheses. The inner pair builds the tuple, and the outer pair is the method call.
Common errors
Passing a list instead of a tuple
The argument must be a str or a tuple of strings. A list raises TypeError.
name = "report.csv"
try:
name.endswith([".csv", ".tsv"])
except TypeError as error:
print("TypeError:", error)
print(name.endswith(tuple([".csv", ".tsv"]))) # TrueIf your suffixes are stored in a list, convert it with tuple(...).
Forgetting case
Matching is case-sensitive. "REPORT.CSV".endswith(".csv") is False. Normalize first, as in the case-folding chapter, for example with name.lower().endswith(".csv").
Using an empty tuple
An empty tuple matches nothing, so the result is always False. A single empty string matches everything, so "abc".startswith("") is True. Both surprises show up when a configuration list turns out to be empty or contains a blank entry.
print("abc".startswith(())) # False
print("abc".startswith("")) # TrueUsing start and end positions
Both methods accept optional start and end arguments. They restrict the test to a slice of the string without creating that slice.
line = "ID: 42"
print(line.startswith("42", 4)) # True
print(line.startswith("ID", 0, 2)) # True
print(line.endswith("4", 0, 5)) # TrueWith endswith, the end position limits where the string is considered to finish. In the last call, the text examined is "ID: 4", so it ends with "4".
A practical use: filtering a list
Combining a tuple with a loop gives a compact filter.
files = ["a.csv", "b.txt", "c.tsv", "data_1.csv", "notes.md"]
tables = [f for f in files if f.endswith((".csv", ".tsv"))]
print(tables) # ['a.csv', 'c.tsv', 'data_1.csv']
reports = [f for f in files if f.startswith("data")]
print(reports) # ['data_1.csv']Exercises
Exercise
Write a condition that is True when the string path ends in .jpg, .jpeg, or .png, ignoring case. Why does path.endswith([".jpg", ".png"]) fail?
Show answer
Use path.lower().endswith((".jpg", ".jpeg", ".png")). Lowercasing handles case, and the tuple tests all three suffixes in one call. The list version fails because endswith accepts only a string or a tuple of strings, so a list raises TypeError.
Exercise
What do "abc".startswith(()) and "abc".startswith("") return, and why?
Show answer
The first returns False because an empty tuple contains no prefix that could match. The second returns True because every string begins with the empty string.