python Template中substitute()的使用

 在docker的harbor部署的过程中,prepare 这个脚本就是根据harbor.cfg的配置变量,然后根据template生成最终的配置文件

在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:Python27libstring.py", line 172, in substitute
    return self.pattern.sub(convert, self.template)
  File "C:Python27libstring.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上运行报错,后来试了一下,冒失后面的版本不支持“()”。使用“{}”或是不写括号是没有问题的。

 

原文地址:https://www.cnblogs.com/robinunix/p/10838175.html