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.
Code
# 位置参数按顺序填充
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 302How 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
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.