Python字符串模板替换_Template模块使用

python 的 string.template 模块提供安全、简洁的字符串替换,不解析表达式,避免代码注入;支持 $name/${name} 占位符、$$ 转义、safe_substitute 容错及自定义分隔符。

Python字符串模板替换_Template模块使用

Python 的 string.Template 模块提供了一种简单、安全的字符串替换方式,特别适合面向用户输入或需要避免代码注入的场景。

为什么用 Template 而不是 % 或 f-string?

string.Template 的语法更简洁、容错性更强,不解析表达式,不会执行任意代码,因此比 % 格式化或 f-string 更安全。例如用户提交的模板字符串中若含 ${user_input},Template 只做字面替换;而用 eval 或 f-string 动态拼接则可能引发安全问题。

它默认使用 $name${name} 占位符,也支持自定义分隔符,适合生成配置文件、邮件模板、HTML 片段等。

基础用法:substitute() 和 safe_substitute()

最常用的是 substitute()safe_substitute() 两个方法:

立即学习Python免费学习笔记(深入)”;

  • substitute(mapping, **kws):严格匹配,缺一个占位符就抛 KeyError
  • safe_substitute(mapping, **kws):缺失键时保留原占位符(如 $missing 不变),适合不确定是否提供全部变量的场景

示例:

 from string import Template t = Template('Hello $name, you have $count messages.') print(t.substitute(name='Alice', count=5))           # Hello Alice, you have 5 messages. print(t.safe_substitute(name='Bob'))                # Hello Bob, you have $count messages. 

支持嵌套与转义写法

占位符可写成 ${name} 形式,便于在相邻字符中明确边界,比如 ${name}123 不会误识别为 $name123。双美元符号 $$ 表示字面量 $

 t = Template('Price: $$${price} (tax included)') print(t.substitute(price=99.9))  # Price: $99.9 (tax included) 

自定义分隔符(进阶用法)

继承 Template 类并重写 delimiter 和/或 idpattern,可适配其他模板风格,例如用 [[name]] 替代 $name

 from string import Template <p>class DoubleBracketTemplate(Template): delimiter = '[[' pattern = r''' [[ (?: (?P<escaped>[[) | (?P<named>[_a-z][_a-z0-9]<em>) ]] | (?P<braced>[_a-z][_a-z0-9]</em>) ]] | (?P<invalid>) ) '''</p><p>t = DoubleBracketTemplate('Welcome [[name]]! You have [[count]] items.') print(t.substitute(name='Tom', count=3))  # Welcome Tom! You have 3 items.</p>