首页 > 学院 > 开发设计 > 正文

pythonTemplate中substitute()的使用

2019-11-14 17:27:08
字体:
来源:转载
供稿:网友

在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上运行报错,后来试了一下,冒失后面的版本不支持“()”。使用“{}”或是不写括号是没有问题的。

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表