摘自:python參考手冊.
string模塊定義了一種新字符串類型Template,簡化了特定的字符串置換操作,
Template定義一個類
1.template(s), #s是字符串
s='hello,$world!' #template 的置換符屬性delimiter 默認是$,
2.t=template(s) #定義template的對象
template的對象t支持的方法
3.t.substitute(m,[,**kwargs]) #其中m是一個字典(或一個關鍵字參數列表),會對字符串s進行關鍵字置換,
t.substitute({'world':'nimei'})
再打印s。發現world被替換成nimei
>>> from string import Template >>> s='hello,$world!' >>> t=Template(s) >>> t.substitute({'world':'nimei'}) 'hello,nimei!' >>>
轉載!
#!/usr/bin/python #coding :utf-8 from string import Template class MyTemplate(Template): """docstring for MyTemplate""" delimiter = '#' def _test(): s = '#who likes #what' t = MyTemplate(s) d = {'who': 'jianpx', 'what': 'mac'} print t.substitute(d) print MyTemplate.delimiter print Template.delimiter if __name__ == '__main__': _test()
打印結果:
>>>
jianpx likes mac
#
$
