string Template Substitutes Variables
Render notification copy with string.Template: substitute fails loudly on missing variables, safe_substitute keeps unknown tokens, ${name} disambiguates.
Code
from string import Template
# $identifier 占位符:模板变量与逻辑分离,文案可外置
template = Template("deploy $service to $env (build $build)")
rendered = template.substitute(service="billing", env="staging", build="2026.11.12")
print(rendered)
# 缺失变量抛 KeyError:宁可失败也不渲染半截文案
try:
template.substitute(service="billing")
except KeyError as error:
print("missing:", error)
# safe_substitute 保留未匹配的 $token,适合分阶段渲染
partial = template.safe_substitute(service="billing")
print(partial)
# ${name} 形式消除歧义:变量名紧贴普通文本时使用
plural = Template("${noun}s")
print(plural.substitute(noun="status"))Output
Captured from a sandboxed run of this snippet in the build pipeline.
deploy billing to staging (build 2026.11.12)
missing: 'env'
deploy billing to $env (build $build)
statussHow the snippet works
The file’s state is a handful of top-level bindings: template, rendered, partial, plural.
Applying it
The demo output is labeled (missing:), so every printed line maps back to its originating operation.
Statements that matter
except KeyError as error:
print("missing:", error)
Interactive Tools for This Topic
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.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Every import resolves inside the standard library — `string`. Its state lives in module-level bindings: `template`, `rendered`, `partial`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.