← 中文资源

简体中文版本

string.Template 替换模板变量

string.Template 用 $identifier 占位符渲染文案:substitute 遇缺失变量抛 KeyError 宁可失败,safe_substitute 保留未知 $token,${name} 消除边界歧义。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

deploy billing to staging (build 2026.11.12)
missing: 'env'
deploy billing to $env (build $build)
statuss

实现说明

顶层就这几处状态:template、rendered、partial、plural。

使用要点

  • 跑完文件,输出里会留下标记——missing:。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 全部导入都来自标准库:string。 文件用顶层绑定保存自己的状态:template、rendered、partial。

核心语句

except KeyError as error:
    print("missing:", error)

代码示例

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"))