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
    

      

  • 相关阅读:
    TweenLite简单运用
    nodejs 重定向 (redirect + writeHead(Location))
    Nodejs Web模块( readFile 根据请求跳转到响应html )
    Express框架(http服务器 + 路由)
    AI 学习路线
    implicitly_wait()隐式等待
    Python 爬虫基础Selenium
    Selenium2+python自动化15-select下拉框
    python selenium while 循环
    jupyter notebook修改默认路径和浏览器
  • 原文地址:https://www.cnblogs.com/subic/p/6552752.html
Copyright © 2011-2022 走看看