浅析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
#
$

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM