登录
首页 >  文章 >  python教程

Python字符串模板替换技巧

时间:2026-04-01 11:03:22 330浏览 收藏

Python 的 `string.Template` 模块提供了一种简洁、安全且高度可控的字符串替换方案,特别适用于处理用户输入、生成配置文件、邮件模板或HTML片段等需防范代码注入风险的场景;它不解析表达式、不执行任意代码,仅做字面量占位符替换(支持 `$name` 和 `${name}` 语法、`$$` 转义、`safe_substitute` 容错机制),还可通过继承自定义分隔符(如 `[[name]]`),在安全性、可读性与灵活性之间取得绝佳平衡——是 `%` 格式化和 f-string 在敏感场景下的理想替代。

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() 两个方法:

  • 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]</braced></em>) ]] |
(?P<invalid>)
)
'''</invalid></named></escaped></p><p>t = DoubleBracketTemplate('Welcome [[name]]! You have [[count]] items.')
print(t.substitute(name='Tom', count=3))  # Welcome Tom! You have 3 items.</p>

好了,本文到此结束,带大家了解了《Python字符串模板替换技巧》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多文章知识!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>