str.format Reuses Templates From Variables

Render strings with str.format positional, named, and indexed fields — the one path where the template itself can live in a variable, unlike f-strings.

PythonCli Tooling

Code

pythonsnippet
16 lines
# 位置参数按顺序填充
print("{} uploaded {} files".format("alice", 3))

# 数字可以带格式说明符,与 f-string 同一套 mini language
print("{:.1f}%".format(97.44))

# 命名参数:模板即文档,重排不串位
print("{user} -> {role}".format(user="bob", role="admin"))

# 索引复用同一个参数,不需要重复传入
print("{0} vs {0}".format("staging"))

# format 的一大优势:模板可以来自变量,f-string 做不到
template = "GET {path} {status}"
for path, status in [("/api", 200), ("/login", 302)]:
    print(template.format(path=path, status=status))

Output

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

alice uploaded 3 files
97.4%
bob -> admin
staging vs staging
GET /api 200
GET /login 302

How it works

for path, status in [("/api", 200), ("/login", 302)] is the loop that carries the per-item work.

Top-level bindings template hold the demo state — nothing sits inside a function scope.

Watch out for

  • No install step: all APIs used ship with the platform.

Core lines

for path, status in [("/api", 200), ("/login", 302)]:
    print(template.format(path=path, status=status))

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `template`.