startswith And endswith Match Prefix Tuples

startswith and endswith accept tuples, so one call matches any of several prefixes or suffixes instead of chaining or-ed string comparisons.

PythonData Integrity

Code

pythonsnippet
19 lines
logs = [
    "app.log",
    "error.log",
    "data.json",
    "notes.txt",
    "access.log.1",
    "debug.LOG",
    "report.pdf",
]

# tuple argument: 一次匹配多个后缀/前缀,不必手写 or 链
log_files = [name for name in logs if name.lower().endswith((".log", ".txt"))]
print("logs :", log_files)

rotated = [name for name in logs if name.startswith(("access", "debug", "app"))]
print("match:", rotated)

json_only = [name for name in logs if name.endswith(".json")]
print("json :", json_only)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

logs : ['app.log', 'error.log', 'notes.txt', 'debug.LOG']
match: ['app.log', 'access.log.1', 'debug.LOG']
json : ['data.json']

How it works

Top-level bindings logs, log_files, rotated, json_only hold the demo state — nothing sits inside a function scope.

Putting it to use

Look for the logs :, match:, json : prefixes when the file runs; they tie each line to its step.

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `logs`, `log_files`, `rotated`.