Python string.Template 的使用

57 阅读1分钟

在Python中,string.Template 提供了一种简单且安全的字符串替换机制。
string.Template 的使用主要分为以下两个步骤:

%%{init: {"theme": "base", "themeVariables": { "background": "#f5f7fa", "primaryColor": "#0066CC", "primaryBorderColor": "#0052A3", "primaryTextColor": "#ffffff", "lineColor": "#0066CC", "fontFamily": "Microsoft YaHei, sans-serif" } } }%%
graph LR
1.创建模板对象 ---> 2.进行数据替换

创建模板基础语法: | string.Template(template_string) |
将包含占位符的字符串转换为模板对象

数据替换基础语法:|template.substitute(mapping)/template.safe_substitute(mapping) |
用实际数据填充模板中的占位符

  • substitute()严格替换。要求提供的字典包含模板中所有占位符对应的键。如果缺少某个键,它会抛出 KeyError异常。这适用于数据完整、确保替换全面的场景。
  • safe_substitute()安全替换。这是更常用、更容错的方法。它只会替换字典中存在的键对应的占位符,对于缺少的键,则保留原占位符不变,而不会报错。这在处理用户输入或不完整数据时特别有用。

1.模块导入

from string import Template

2.基础用法

from string import Template

# 模板中有三个变量:${name}, ${language}, ${mood}
template_string = "${name} 觉得用 ${language} 编程很 ${mood}!"
template = Template(template_string)

# 数据中缺少 ${mood} 变量
incomplete_data = {"name": "你", "language": "Python"}

# 使用 safe_substitute,缺少的 ${mood} 保持不变
safe_result = template.safe_substitute(incomplete_data)
print("safe_substitute 结果: " + safe_result)  # 输出:你 觉得用 Python 编程很 $mood!

# 尝试使用 substitute,会引发 KeyError
try:
    strict_result = template.substitute(incomplete_data)
except KeyError as e:
    print("substitute 出错:缺少变量", str(e))

3.生成HTML片段

模板文件 (user_card.html) 内容:

<div class="user-card">
    <h3>$username</h3>
    <p>邮箱: <a href="mailto:$email">$email</a></p>
    <p>注册时间: $register_date</p>
    <p>状态: <span class="status-$status">$status_text</span></p>
    <p>最后登录: $last_login</p>
</div>

Python代码:

from string import Template

# 读取HTML模板
with open('user_card.html', 'r', encoding='utf-8') as f:
    html_template = Template(f.read())

# 用户数据
users_data = [
    {
        'username': 'AliceSmith',
        'email': 'alice@example.com',
        'register_date': '2023-05-10',
        'status': 'active',
        'status_text': '活跃',
        'last_login': '2024-01-15 09:30:00'
    },
    {
        'username': 'BobJohnson', 
        'email': 'bob@example.com',
        'register_date': '2024-01-10',
        'status': 'new',
        'status_text': '新用户',
        'last_login': '2024-01-15 14:20:00'
    }
]

# 为每个用户生成HTML卡片
for user in users_data:
    html_card = html_template.safe_substitute(user)
    print(html_card)
    print("\n" + "="*50 + "\n")