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.
Code
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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.