Python 官方文档:入门教程 => 点击学习
template是python中的string库的一部分 使用template可以不编辑应用就可以改变其中的数据 模板还可以被他的子类修改 template是含有占位符的字符串 用字典将值映射到模板中 占位符后面跟着的变量名要
from string import Template
def main():
cart = []
cart.append(dict(item='coke',price=11,Qty= 1))
cart.append(dict(item='cake',price=12,qty=6))
cart.append(dict(item='fish',price = 1,qty =4))
t = Template("$qty * $item = $price")
total = 0
print "Cart"
for data in cart:
print t.substitute(data)
total += data["price"]
print "Total: %s"%(total,)
if __name__ == "__main__":
main()
from string import Template
class MyTemplate(Template):
delimiter = '&'
def main():
cart = []
cart.append(dict(item='coke',price=11,qty= 1))
cart.append(dict(item='cake',price=12,qty=6))
cart.append(dict(item='fish',price = 1,qty =4))
t = MyTemplate("&qty * &item = &price")
total = 0
print "Cart"
for data in cart:
print t.substitute(data)
total += data["price"]
print "Total: %s"%(total,)
if __name__ == "__main__":
main()
Cart
1 * coke = 11
6 * cake = 12
4 * fish = 1
Total: 24
>>> t = Template(“$you owe me $$0.”)
>>> t.substitute(dict(you=’James’))
“James owe me $0.”
>>> t = Template(“The ${back}yard is far away.”)
>>> t.substitute(dict(back=’ship’))
“The shipyard is far away.”
--结束END--
本文标题: [笔记]python template
本文链接: https://lsjlt.com/news/188960.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0