zoukankan      html  css  js  c++  java
  • Python中Template使用的一个小技巧

    Python中Template是string中的一个类,可以将字符串的格式固定下来,重复利用。

    from string import Template
    s = Template("there are ${howmany} ${lang} Quotation symbols")
    print s.substitute(lang='Python',howmany=3)
    >>>there are 3  Python Quotation symbols
    

    用法很简单,先生成一个模板实例s,然后调用替换函数substitute()将模板中的两个地方替换掉。替换的内容是通过字典对调用的,所以下面(lang='Python',howmany=3)出现的顺序可以不用严格的和模板中的一样。当然不用括号也是可以的。

    from string import Template
    s = Template("there are $howmany $lang Quotation symbols")
    print s.substitute(lang='Python',howmany=3)
    >>>there are 3  Python Quotation symbols

    注意:在使用${howmany} ${lang}时候,括号里的内容和括号要紧贴着,不然会报错。

    from string import Template
    s = Template("there are ${ howmany } ${lang} Quotation symbols")
    print s.substitute(lang='Python',howmany=3)
    >>>Traceback (most recent call last):
      File "E:/�������/201703/DeepLearning/neural-networks-and-deep-learning-master/src/validation.py", line 39, in <module>
        print s.substitute(lang='Python',howmany=3)
      File "C:\Users\wangxin\Anaconda2\lib\string.py", line 176, in substitute
        return self.pattern.sub(convert, self.template)
      File "C:\Users\wangxin\Anaconda2\lib\string.py", line 173, in convert
        self._invalid(mo)
      File "C:\Users\wangxin\Anaconda2\lib\string.py", line 146, in _invalid
        (lineno, colno))
    ValueError: Invalid placeholder in string: line 1, col 11
    

    当然在使用substitute()的时候,对应的关键字和值都要给出,不然会报错。

    from string import Template
    s = Template("there are ${ howmany } ${lang} Quotation symbols")
    print s.substitute(lang='Python')
    >>>Traceback (most recent call last):
      File "E:/�������/201703/DeepLearning/neural-networks-and-deep-learning-master/src/validation.py", line 39, in <module>
        print s.substitute(lang='Python')
      File "C:\Users\wangxin\Anaconda2\lib\string.py", line 176, in substitute
        return self.pattern.sub(convert, self.template)
      File "C:\Users\wangxin\Anaconda2\lib\string.py", line 166, in convert
        val = mapping[named]
    KeyError: 'howmany'
    

    使用safe_substitute()可以避免报错.

    from string import Template
    s = Template("there are ${howmany} ${lang} Quotation symbols")
    print s.safe_substitute(lang='Python')
    >>>there are ${howmany} Python Quotation symbols
    

      

  • 相关阅读:
    Linux终端以及bash
    初识VIM
    基础命令
    目录结构和命令
    Xshell连接Centos7.5和yum
    Linux的发展史和centos7的安装
    学习方法以及计算机硬件基础
    mysql、MariaDB的简单操作
    yum 软件管理器
    基础面试题
  • 原文地址:https://www.cnblogs.com/subic/p/6552752.html
Copyright © 2011-2022 走看看