python的string模板


string模板提供了另一种格式化值得方法:模板字符串。它的工作方式类似于很多unixShell里的变量替换。如下表示:substitute这个模板方法会用穿都进来的关键字参数foo替换字符串中的$foo。
>>> from string import Template
>>> s=Template('$x,silence.$x'!)
SyntaxError: invalid syntax
>>> s=Template('$x,silence.$x')
>>> s.substitute(x='you')
'you,silence.you'


如果替换字段是单词的一部分,那么参数名就必须用括号包括起来i,从而准确指明结尾:
>>> s=Template('It is ${x}ence!')
>>> s.substitute(x='sil')
'It is silence!


可以使用$$插入美元符
>>> s=Template('make $$ selling $x!')
>>> s.substitute(x='demo')
'make $ selling demo!'


除了关键字以外,还可以使用字典变量提供值/名称对.
>>> s=Template('a $thing must never $action.')
>>> d={}
>>> d['thing']='gentleman'
>>> d['action']='show his socks'
>>> s.substitute(d)
'a gentleman must never show his socks.'

方法safe_substitute不会因为缺少值或者不正确使用$字符而出错。

以上来自学习的摘要。


评论关闭