zoukankan      html  css  js  c++  java
  • python Template中substitute()的使用

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

  • 相关阅读:
    标准粒子群算法(PSO)
    Java开发中的23种设计模式详解
    分布式事务
    sjk 分页
    有用吗2
    有用吗1
    存储过程
    在虚拟机Linux安装Redis
    ajax调用WebAPI添加数据
    SVN安装和使用(简单版)
  • 原文地址:https://www.cnblogs.com/mouseIT/p/4173513.html
Copyright © 2011-2022 走看看