《Python核心编程第二版》笔记(五)

2019-09-26  本文已影响0人  yousa_
  • python字符串模板:Template

Template的优势是不用去记住所有相关细节的输出形式。
Template对象有两个方法:substitute()safe_substitute(),前者更为严谨,在key缺少的情况下会报一个KeyError异常出来,而后者在缺少key时,会原封不动的把字符串显示出来。

from string import Template
s = Template("There are ${howmany} years I havn't see ${who}.")
print(s.substitute(howmany=12, who='you'))
>>> There are 12 years I havn't see you.
print(s.safe_substitute(howmany=12))
>>> There are 12 years I havn't see ${who}.
上一篇 下一篇

猜你喜欢

热点阅读