Python Template中substitute的使用

在python中Template可以将字符串的格式固定下来,重复利用。

Template属于string中的一个类,要使用他的话可以用以下方式调用:

from string import Template

我们使用以下代码:

>>> s = Template('There  ${moneyType} is  ${money}')
>>> print s.substitute(moneyType = 'Dollar',money=12)

运行结果显示“There Dollar is 12”这样我们就可以替换其中的数据了。但是我们要替换其中的一个数据呢?

>>> print s.substitute(moneyType = 'Dollar')

Traceback (most recent call last):
  File "<pyshell#509>", line 1, in <module>
    print s.substitute(moneyType = 'Dollar')
  File "C:\Python27\lib\string.py", line 172, in substitute
    return self.pattern.sub(convert, self.template)
  File "C:\Python27\lib\string.py", line 162, in convert
    val = mapping[named]
KeyError: 'money'

复制代码报错了。看来这样不行。这是就要用到safe_substitute了

>>> print s.safe_substitute(moneyType = 'Dollar')
There  Dollar is  ${money}

注意:我之前看的参考书$符后使用的是“()”括号,但是我在2.7.9上运行报错,后来试了一下,冒失后面的版本不支持“()”。使用“{}”或是不写括号是没有问题的。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值