Python:字符串模板(string.Template)
在 Python 中,除了 %、.format()、f-string 三种常见的字符串格式化方式外,标准库 string 还提供了一种更安全、可本地化的机制:string.Template。
它以 $ 符号为占位标记,适合需要在受控环境中进行字符串替换的场景,例如 用户输入模板、配置文件、Web 表单 。
一、基本概念
string.Template 是 string 模块中的一个类,通过定义模板字符串 Template 对象,可以用指定的数据字典进行变量替换。
基本语法如下:
from string import Template
tmpl =Template("Hello,$name!")
print(tmpl.substitute(name="Alice"))
二、占位符语法
Template 的占位符以 $ 开头,有以下几种形式:
| 形式 | 示例 | 含义 |
| $identifier | $user | 简单变量名 |
| ${identifier} | ${user} |
带花括号的变量名,用于避免歧义 |
$$ |
$$100 | 转义形式,输出一个 $ 符号本身 |
from string import Template
tmpl = Template("Price: $$${amount}")
print(tmpl.substitute(amount=99))
说明:
${amount} 确保模板正确识别变量边界;
若写成 $amounts 将被解释为变量 amounts 而非 amount + s。
三、substitute() 与 safe_substitute()
Template 对象提供两种主要替换方法:
1、substitute(mapping, **kwargs) 强制替换所有变量,若模板中出现未定义的变量会抛出 KeyError:
from string import Template
tmpl = Template("User:$name, Age:$age")
# 输出:User: Alice, Age: 23
print(tmpl.substitute(name="Alice", age=23))
# 缺少变量时:
print(tmpl.substitute(name="Alice")) # KeyError: 'age'
2、safe_substitute(mapping, **kwargs)
忽略缺失变量并保留原样,常用于用户输入或不完整数据的情境
from string import Template
tmpl = Template("Hello,$name! You are $age years old.")
# 输出:Hello,Bob! You are $age years old.
print(tmpl.safe_substitute(name="Bob"))
四、从字典或对象批量替换
Template 天然支持映射(dict)对象作为参数:
from string import Template
info = {"user": "Tom", "lang": "Python"}
tmpl = Template("User: $user, Language: $lang")
print(tmpl.substitute(info)) # 输出:User: Tom, Language: Python
也可使用 safe_substitute() 防止键缺失导致异常。
五、自定义模板变量分隔符
Template 类可通过子类化的方式,自定义变量前缀或分隔符。
from string import Template
class MyTemplate(Template):
delimiter = "%"
tmpl = MyTemplate("Welcome, %user!")
print(tmpl.substitute(user="Alice")) # 输出:Welcome, Alice!
说明:
🔹 默认 delimiter 为 $;
🔹 可以改为 %、@ 等任意符号;
🔹 这种方式常用于与旧系统或第三方模板语法兼容。
六、模板文件的应用
Template 不仅能用于内联字符串,也可处理外部文本模板。
from string import Template
with open("template.txt", encoding="utf-8") as f:
content = f.read()
tmpl = Template(content)
result = tmpl.safe_substitute(name="Alice", score=95)
print(result)
emplate.txt 内容如下:
学生:$name
成绩:$score
输出:
学生:Alice
成绩:95
适用于配置文件、日志格式模板、报告生成等场景。
七、进阶:动态模板组合
Template 可与多层字典结合实现多级模板填充。
from string import Template
user = {"name": "Alice", "lang": "Python"}
tmpl_outer = Template("Info:$inner")
tmpl_inner = Template("User=$name, Lang=$lang")
inner = tmpl_inner.substitute(user)
print(tmpl_outer.substitute(inner=inner)) # 输出:Info: User=Alice, Lang=Python
这种“模板嵌套”机制使 Template 在复杂报表生成中非常灵活。
八、常见错误与注意事项
1、未定义变量抛 KeyError
使用 safe_substitute() 可避免。
2、变量名冲突
若模板中有 $namex 与 $name,需使用 ${name} 确保正确边界。
3、转义字符错误
$ 需要写成 $$ 以输出 $ 本身。
4、性能不如 f-string
在大量重复替换场景下应缓存 Template 对象。
5、对比 f-string 与 Template
简而言之,f-string 适合开发者内部逻辑;Template 适合安全模板与国际化应用。

浙公网安备 33010602011771号