python~ from string import Template

Template为python string提供的一个字符串模板功能。主要用于文本处理

s = Template('$what is  $how')
>>> s.substitute(what = "this food",how ="yummy")
'this food is  yummy'

Template有两个substitute方法。
用substitute时。所带的keywords必须被替代字符串配对,不然会抛出ValueError异常
safe_substitute不会抛出异常,能配对的配对。不能配对的保留原来的值

>>> s.safe_substitute(what = "this food")
'this food is  $how'
>>>s.safe_substitute()
'$what is  $how'
>>> s.safe_substitute(how="yummy")
'$what is  yummy'

另外substitute可以接受两种类型的参数。mapping and **kwds,mapping is any dictionary-like object with keys 。用法如下

>>> s = Template('$what is  $how')
>>> d = dict(what='tim')
>>> s.safe_substitute(d)
'tim is  $how'

当mapping与 kwd 同时存在时。kwds优先

>>> test_s = Template('$what is  $how')
>>> d=dict(what = 'time')
>>> test_s.safe_substitute(d,what="ok")
'ok is  $how'

可以继承Template来重载delimiter等属性,记录在这,以后要用的时候再翻

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值