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

     

  • 相关阅读:
    提升开发效率的十个工具
    JQuery常用函数及功能小结
    jquery-validation 学习总结
    JavaScript:避免代码的重复执行
    18 个最好的CSS框架用于提高开发效率
    如何书写高质量的jQuery代码
    13个 ASP.NET MVC 的扩展
    CSS_LESS 语法/函数详解
    21个值得收藏的Javascript技巧
    JQuery常用功能的性能优化
  • 原文地址:https://www.cnblogs.com/robinunix/p/10838175.html
Copyright © 2011-2022 走看看