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

     

  • 相关阅读:
    Bootstrap留言板界面练习
    Bootstrap 学习
    web | [GXYCTF2019]禁止套娃
    re | [GKCTF2020]WannaReverse
    PE文件结构 | 在PE文件的空白区添加代码
    PE文件结构 | RVA与FOA的转换
    re | [NPUCTF2020]BasicASM
    win32 | WinSock2网络编程 | socket-tcp通信
    web | flask 修饰器实现原理
    运维 | 配置LNMP | 基于docker.ubuntu:16.04
  • 原文地址:https://www.cnblogs.com/robinunix/p/10838175.html
Copyright © 2011-2022 走看看