python 模板打印_模板-用于纯文本输出的Python技术或简单模板系统

您可以使用标准库字符串模板:

所以你有一个文件src与

$title

...

$subtitle

...

$list

和一本字典

d={ 'title':title, 'subtitle':subtitle, 'list':'\n'.join(list) }

那很简单

from string import Template

#open the file

filein = open( 'foo.txt' )

#read it

src = Template( filein.read() )

#do the substitution

src.substitute(d)

然后可以打印src

当然,正如Jammon所说,您还有许多其他好的模板引擎(这取决于您要执行的操作。标准字符串模板可能是最简单的)

完整的工作示例

foo.txt

$title

...

$subtitle

...

$list

example.py

from string import Template

#open the file

filein = open( 'foo.txt' )

#read it

src = Template( filein.read() )

#document data

title = "This is the title"

subtitle = "And this is the subtitle"

list = ['first', 'second', 'third']

d={ 'title':title, 'subtitle':subtitle, 'list':'\n'.join(list) }

#do the substitution

result = src.substitute(d)

print result

然后运行example.py

$ python example.py

This is the title

...

And this is the subtitle

...

first

second

third

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值