Python中如何动态格式化模板字符串?如何用CSV字段替换占位符?
Python动态模板字符串格式化与CSV数据填充指南
问题1:如何在Python中动态格式化模板字符串?
Python提供了几种灵活的方式来处理动态模板字符串,不管你的占位符是什么,都能轻松替换:
方法1:使用
str.format()配合字典解包
这是日常开发中最常用的方式,适合占位符对应键明确的场景。把数据存在字典里,用**解包后传给format()即可自动匹配替换:template = "Hello {username}, your balance is ${balance}." user_data = {"username": "johndoe", "balance": 450.75} result = template.format(**user_data) print(result) # 输出: Hello johndoe, your balance is $450.75.哪怕模板里的占位符是动态变化的,只要字典包含对应的键,就能自动完成匹配。
方法2:使用
string.Template类
这个方法更安全,适合处理用户输入的模板(能避免格式字符串注入风险),占位符以$开头:from string import Template template = Template("Hi $first_name, your order #$order_id has shipped!") order_data = {"first_name": "Emily", "order_id": 12345} result = template.substitute(order_data) print(result) # 输出: Hi Emily, your order #12345 has shipped!要是担心有缺失的键,可以用
safe_substitute(),它会保留缺失的占位符而不是直接抛出错误。
问题2:用CSV数据替换模板中的占位符
结合CSV读取和上面的模板格式化方法,就能轻松实现需求,步骤如下:
- 读取CSV文件为字典格式:用
csv.DictReader可以直接把每一行转换成以表头为键的字典,完美匹配模板里的占位符。 - 遍历数据并格式化模板:对每一行数据,用上述格式化方法替换模板中的占位符(不管占位符是CSV字段的哪一个子集)。
示例代码:
import csv from string import Template # 定义你的模板字符串(占位符是CSV字段的子集) template = Template("Hi $first_name $last_name, thank you for your purchase on $order_date!") # 读取CSV文件 with open("customer_orders.csv", mode="r", encoding="utf-8") as csv_file: # DictReader会自动用表头作为字典的键 reader = csv.DictReader(csv_file) for customer in reader: # 用Template的substitute替换占位符 formatted_message = template.substitute(customer) # 或者用str.format():formatted_message = "Hi {first_name} {last_name}, thank you for your purchase on {order_date}!".format(**customer) print(formatted_message)
额外处理:应对缺失字段的情况
如果CSV里某些行缺少模板中的字段,用safe_substitute()代替substitute(),这样会保留占位符而不报错:
formatted_message = template.safe_substitute(customer)
或者你可以先过滤出模板需要的字段,避免不必要的键:
# 先提取模板中用到的所有占位符(针对Template的$格式) placeholders = [t[1] for t in Template.pattern.findall(template.template) if t[1]] # 过滤出CSV行中存在的占位符对应数据 filtered_data = {k: customer[k] for k in placeholders if k in customer} formatted_message = template.substitute(filtered_data)
内容的提问来源于stack exchange,提问作者Sudhanshu Mishra
相关产品推荐
相关产品推荐

