Python:Template使用指南

来源:互联网 发布:淘宝国际卖家 编辑:程序博客网 时间:2024/06/08 05:39

17年7月第5篇日志
七月快要结束,八月马上就要开始。最近人工智能的势头越来越过,不过这个浪潮下谁留下来,谁能踏实作出新的成就,一切都未可知。
本周带来的博客主要讲解Template的使用,这篇博客是基于python3写的,因为最近在做微信的项目采用的语言就是python 3,下面进入正题。
Template无疑是一个好东西,可以将字符串的格式固定下来,Template属于string中的一个类,所以要使用的话可以用以下方式调用:

from string import Template

template 有个特殊的标识符使xxx,其中xxx是满足python命名规则的字符串,即不能以数字开头,不能为关键字等,如果xxxxxxaaa{xxx}aaa

from string import Templates=Template("There $a and ${b}s")print (s.substitute(a='apple',b='banana'))print (s.safe_substitute(a='apple',b='banbana'))

运行结果:

PycharmProjects/untitled/reply.pyThere apple and bananasThere apple and banbanasProcess finished with exit code 0

Template还可以通过字典来直接传递数据:

from string import Templates=Template("There $a and ${b}s")d={'a':'apple','b':'banbana'}print(s.substitute(d))

运行结果:

from string import Templates=Template("There $a and ${b}s")d={'a':'apple','b':'banbana'}print(s.substitute(d))

Template的实现方式是首先通过Template初始化一个字符串。这些字符串中包含了一个个key。通过调用substitute或safe_subsititute,将key值与方法中传递过来的参数对应上,从而实现在指定的位置导入字符串。这个方式的一个好处是不用像print ‘%s’之类的方式,各个参数的顺序必须固定,只要key是正确的,值就能正确插入。
substitute是一个严肃的方法,如果有key没有输入,那就一定会报错。虽然会很难看,但是可以发现问题。safe_substitute则不会报错,而是将$xxx直接输入到结果字符串中。例如:

from string import Templates=Template("There $a and ${b}s")d={'a':'apple'}#print(s.substitute(d))print(s.safe_substitute(d))

结果:

PycharmProjects/untitled/reply.pyThere apple and ${b}sProcess finished with exit code 0

通过safe_substitute可以保证你的程序总是对的。
同时在Template中还可以通过继承重写的方式,进行一些个性化的修改。通过修改delimiter字段可以将$字符改变为其他字符如“#”,不过新的标示符需要符合正则表达式的规范。通过修改idpattern可以修改key的命名规则,比如说规定第一个字符开头必须是a,这对规范命名倒是很有好处。当然,这也是通过正则表示实现的。

from string import Templateclass 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()

上面就是对于Template的详细的讲解,希望能够给大家带来帮助,上面的所示内容,均通过代码的实际验证,可以保证准确无误。

原创粉丝点击