Section 157.1:使用模板的简单数据输出程序
from string import Template
data = dict(item="candy", price=8, qty=2)
# 定义模板
t = Template("Simon bought $qty $item for $price dollar")
print(t.substitute(data))
输出:
Simon bought 2 candy for 8 dollar

模板支持基于$的替换,而不是基于%的替换。substitute(mapping, keywords)执行模板替换,返回一个新字符串。
mapping是任何类似字典的对象,其键与模板占位符匹配。在这个例子中,price和qty是占位符。也可以使用关键字参数作为占位符。如果两者都存在,关键字参数的占位符优先。
Section 157.2:更改分隔符
你可以将$分隔符更改为其他任何字符。以下示例:
from string import Template
class MyOtherTemplate(Template):
delimiter = "#"
data = dict(id=1, name="Ricardo")
t = MyOtherTemplate("My name is #name and I have the id: #id")
print(t.substitute(data))
输出:
My name is Ricardo and I have the id: 1
