hello!python!

浅析python的string.Template

摘自: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
#
$

 

posted @ 2014-03-10 16:42  你坚持了吗  阅读(7089)  评论(0编辑  收藏  举报
hello!python!