Template为python string提供的一个字符串模板功能。主要用于文本处理
s = Template('$what is $how')>>> s.substitute(what = "this food",how ="yummy")'this food is yummy'Template有两个substitute方法。 用substitute时。所带的keyWords必须被替代字符串配对,不然会抛出ValueError异常 safe_substitute不会抛出异常,能配对的配对。不能配对的保留原来的值
>>> s.safe_substitute(what = "this food")'this food is $how'>>>s.safe_substitute()'$what is $how'>>> s.safe_substitute(how="yummy")'$what is yummy'另外substitute可以接受两种类型的参数。mapping and **kwds,mapping is any dictionary-like object with keys 。用法如下
>>> s = Template('$what is $how')>>> d = dict(what='tim')>>> s.safe_substitute(d)'tim is $how'当mapping与 kwd 同时存在时。kwds优先
>>> test_s = Template('$what is $how')>>> d=dict(what = 'time')>>> test_s.safe_substitute(d,what="ok")'ok is $how'可以继承Template来重载delimiter等属性,记录在这,以后要用的时候再翻
新闻热点
疑难解答