string Template Substitutes Variables

Render notification copy with string.Template: substitute fails loudly on missing variables, safe_substitute keeps unknown tokens, ${name} disambiguates.

PythonCli Tooling

Code

pythonsnippet
21 lines
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)
statuss

How 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

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`.