Template方法应用

Template方法:

template方法是属于string模块下面的一个类,主要作用是可以定义一些模板,传固定参数的值,字符串的格式固定下来,重复利用。
首先先引用这个方法
from string import Template
 
然后先学会使用最常用的两个功能
一:
substitute
具体用法是定义一个字符串模板,然后模板内设定好key值,再使用key-value键值对方法去把模板内的key替换为value值.
>>> Template("${key1} is so beatiful,${key2} said").substitute({"key1":"xiaozhang","key2":"xiaowang"})
'xiaozhang is so beatiful,xiaowang said'
>>>
Template("${key1} is so beatiful,${key2} said")这部分是模板设置的部分,其中key1和key2是要被替换的对象,${key}是固定的写法,当然也可以用写法$key1,来代替,看个人喜好
.substitute({"key1":"xiaozhang","key2":"xiaowang"})这部分是要替换模板内的准备好的内容,通过key来替换模板内的key
 
这个时候如果我们使用的模板内有key2  但是替换内容没有设置key2,就会出现下面的问题:
>>> Template("${key1} is so beatiful,${key2} said").substitute({"key1":"xiaozhang"})
Traceback (most recent call last):
  File "", line 1, in
  File "C:Python27libstring.py", line 176, in substitute
    return self.pattern.sub(convert, self.template)
  File "C:Python27libstring.py", line 166, in convert
    val = mapping[named]
KeyError: 'key2'
这样的话会报错,提示没有这个key,这个时候我可以用到第二个方法。
二:
safe_substitute
这样的话,仍然用一中例子可以看到结果:
>>> Template("${key1} is so beatiful,${key2} said").safe_substitute({"key1":"xiaozhang"})
'xiaozhang is so beatiful,${key2} said'
>>>
虽然这个key在后面未找到,但是也没有提示错误,仍然将原key2模板展示了出来.
然后感觉用着不爽,不符合需求也根据自己需求改模板命名规则。
然后我们继承Template这个类然后重写一下模板key的命名规则
>>> class NewTemplate(Template):
...     delimiter="#"#这个参数是重新设定识别key标识符
...     idpattern="keyd"#这个参数是设置参数命名规则,不写默认是跟python变量命名规则一致
...
修改后结果展示:
>>> NewTemplate("#{key1} is so beatiful,#{key2} said").safe_substitute({"key1":"xiaozhang"})
'xiaozhang is so beatiful,#{key2} said'
 
>>> NewTemplate("${key1} is so beatiful,#{key2} said").safe_substitute({"key1":"xiaozhang"})
'${key1} is so beatiful,#{key2} said'
原文地址:https://www.cnblogs.com/zhangtebie/p/11185802.html