python template_Python中Template使用的一个小技巧

Python中Template是string中的一个类,可以将字符串的格式固定下来,重复利用。

from string import Template

s = Template("there are ${howmany} ${lang} Quotation symbols")

print s.substitute(lang='Python',howmany=3)

>>>there are 3 Python Quotation symbols

用法很简单,先生成一个模板实例s,然后调用替换函数substitute()将模板中的两个地方替换掉。替换的内容是通过字典对调用的,所以下面(lang='Python',howmany=3)出现的顺序可以不用严格的和模板中的一样。当然不用括号也是可以的。

from string import Template

s = Template("there are $howmany $lang Quotation symbols")

print s.substitute(lang='Python',howmany=3)

>>>there are 3 Python Quotation symbols

注意:在使用${howmany} ${lang}时候,括号里的内容和括号要紧贴着,不然会报错。

from string import Template

s = Template("there are ${ howmany } ${lang} Quotation symbols")

print s.substitute(lang='Python',howmany=3)

>>>Traceback (most recent call last):

File "E:/�������/201703/DeepLearning/neural-networks-and-deep-learning-master/src/validation.py", line 39, in

print s.substitute(lang='Python',howmany=3)

File "C:\Users\wangxin\Anaconda2\lib\string.py", line 176, in substitute

return self.pattern.sub(convert, self.template)

File "C:\Users\wangxin\Anaconda2\lib\string.py", line 173, in convert

self._invalid(mo)

File "C:\Users\wangxin\Anaconda2\lib\string.py", line 146, in _invalid

(lineno, colno))

ValueError: Invalid placeholder in string: line 1, col 11

当然在使用substitute()的时候,对应的关键字和值都要给出,不然会报错。

from string import Template

s = Template("there are ${ howmany } ${lang} Quotation symbols")

print s.substitute(lang='Python')

>>>Traceback (most recent call last):

File "E:/�������/201703/DeepLearning/neural-networks-and-deep-learning-master/src/validation.py", line 39, in

print s.substitute(lang='Python')

File "C:\Users\wangxin\Anaconda2\lib\string.py", line 176, in substitute

return self.pattern.sub(convert, self.template)

File "C:\Users\wangxin\Anaconda2\lib\string.py", line 166, in convert

val = mapping[named]

KeyError: 'howmany'

使用safe_substitute()可以避免报错.

from string import Template

s = Template("there are ${howmany} ${lang} Quotation symbols")

print s.safe_substitute(lang='Python')

>>>there are ${howmany} Python Quotation symbols

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值