startswith Matches Prefix Tuples

Validate routing prefixes with str.startswith, which accepts a tuple of candidates and a start offset so one call replaces or-ed comparisons.

PythonForm Validation

Code

pythonsnippet
22 lines
routes = ["/api/v1/users", "/healthz", "/api/v1/orders", "/metrics"]

# 传入元组:一次调用匹配多个前缀
api_routes = [r for r in routes if r.startswith(("/api/", "/metrics"))]
print(api_routes)

# start 控制从哪个偏移开始匹配,不用切片拷贝
s3_key = "backups/2026/db.sql"
print(s3_key.startswith("2026/", 8))

# endswith 同样支持元组,按扩展名分类
for filename in ["a.tar.gz", "b.zip", "c.tar.gz"]:
    kind = "archive" if filename.endswith((".tar.gz", ".zip")) else "unknown"
    print(filename, kind)

# startswith 返回布尔值,可直接做条件路由
def handle(path):
    if path.startswith("/api/"):
        return "api handler"
    return "static"

print(handle("/api/v1/users"), handle("/favicon.ico"))

Output

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

['/api/v1/users', '/api/v1/orders', '/metrics']
True
a.tar.gz archive
b.zip archive
c.tar.gz archive
api handler static

How the snippet works

The tuple form is the headline: r.startswith(("/api/", "/metrics")) matches two prefixes in one call, and the list comprehension over routes filters both API paths and the metrics endpoint without an or chain. s3_key.startswith("2026/", 8) uses the start offset to test only the substring after backups/ — index 8 lands on 2026/ — avoiding a slice copy just for the check.

endswith accepts tuples the same way: the loop classifies "a.tar.gz" and "c.tar.gz" as archive via (".tar.gz", ".zip") while "b.zip" gets unknown. handle closes the file with the boolean-routing pattern — if path.startswith("/api/"): return "api handler", else "static" — so handle("/api/v1/users") and handle("/favicon.ico") print the two branches in one line.

What to watch for

  • The start offset counts characters from position 0, and only that region participates — anything before it is ignored, including would-be matches.
  • Tuples, not lists: startswith(["/api/"]) raises TypeError; the argument must be a tuple.
  • startswith(()) with an empty tuple returns False — convenient as a no-match default.

Using it

The entry-point signature is def handle(path)

The surface worth importing is handle; the helpers around it are private to the snippet.

Key statements

def handle(path):
    if path.startswith("/api/"):
        return "api handler"
    return "static"

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `handle` at load time.