Python 字符串 Template

from string import Template

s = Template('We have ${many} apples at ${where}')
print s.substitute(many = 5,where = 'anhui')
print s.safe_substitute(where = 'xiamen')
print s.safe_substitute(many = 8)

 

    substitute要去全部参数必须填写,否则报错,safe_substitute 则不要求,而是原封不动的把字符串打印出来。

 

    Template 是 格式化字符串很好的替代品。

 

We have 5 apples at anhui
We have ${many} apples at xiamen
We have 8 apples at ${where}
 

你可能感兴趣的:(template)