python的Template

Template无疑是一个好东西,能够将字符串的格式固定下来,重复利用。同时Template也可让开发人员能够分别考虑字符串的格式和其内容了,无形中减轻了开发人员的压力。html

Template属于string中的一个类,因此要使用的话能够用如下方式调用python

from string import Template

Template有个特殊标示符$,它具备如下的规则:
正则表达式

  1. 它的主要实现方式为$xxx,其中xxx是知足python命名规则的字符串,即不能以数字开头,不能为关键字等
    app

  2. 若是$xxx须要和其余字符串接触时,可用{}将xxx包裹起来(之前彷佛使用'()',个人一本参考书上是这样写的,可是如今的版本应该只能使用'{}')。例如,aaa${xxx}aaacode

Template中有两个重要的方法:substitute和safe_substitute.htm

这两个方法均可以经过获取参数返回字符串继承

>>s=Template(There $a and $b)
>>print s.subtitute(a='apple',b='banana')
There apple and banana
>>print s.safe_substitute(a='apple',b='banbana')
There apple and banbana

还能够经过获取字典直接传递数据,像这样开发

>>s=Template(There $a and $b)
>>d={'a':'apple','b':'banbana'}
>>print s.substitute(d)
There apple and banbana

它们之间的差异在于对于参数缺乏时的处理方式。字符串

Template的实现方式是首先经过Template初始化一个字符串。这些字符串中包含了一个个key。经过调用substitute或safe_subsititute,将key值与方法中传递过来的参数对应上,从而实如今指定的位置导入字符串。这个方式的一个好处是不用像print ‘%s’之类的方式,各个参数的顺序必须固定,只要key是正确的,值就能正确插入。经过这种方式,在插入不少数据的时候就能够松口气了。但是即便有这样偷懒的方法,依旧不能保证不出错,若是key少输入了一个怎么办呢?
string

substitute是一个严肃的方法,若是有key没有输入,那就必定会报错。虽然会很难看,可是能够发现问题。

safe_substitute则不会报错,而是将$xxx直接输入到结果字符串中,如

there apple and $b

这样的好处是程序老是对的,不用被一个个错误搞得焦头烂额。


Template能够被继承,它的子类能够进行一些‘个性化’操做...

经过修改delimiter字段能够将$字符改变为其余字符,如“#”,不过新的标示符须要符合正则表达式的规范。

经过修改idpattern能够修改key的命名规则,好比说规定第一个字符开头必须是a,这对规范命名却是颇有好处。固然,这也是经过正则表示实现的。

from string import Template
class MyTemplate(Template):
    delimiter = "#"
    idpattern = "[a][_a-z0-9]*"
def test():
    s='#aa is not #ab'
    t=MyTemplate(s)
    d={'aa':'apple','ab':'banbana'}
    print t.substitute(d)
if __name__=='__main__':
    test()


参考资料:https://docs.python.org/2/library/string.html#template-strings

相关文章
相关标签/搜索