1. string.Template - 轻量级解决方案
Python标准库中的简单模板引擎,适合基本的字符串替换需求。语法简单,安全性高(默认不执行任意代码)。
示例代码:
import string template = string.Template(""" Hello $name, Your order #$order_id is ready for shipment. Estimated delivery: $delivery_date. Thank you for shopping with us! """) # 替换变量 result = template.substitute( name="John Doe", order_id="12345", delivery_date="2023-06-15" ) print(result)
优点
- 无需额外安装
- 语法简单易学
- 安全性高
缺点
- 功能有限
- 不支持复杂逻辑
- 缺少模板继承等高级功能
发表评论