字符串模版:更简单的替代品

新式的字符串Template 对象的引进使得string 模块又重新活了过来,Template 对象有两个方法,substitute()和safe_substitute().前者更为严谨,在key 缺少的情况下它会报一个KeyError 的异常出来,而后者在缺少key 时,直接原封不动的把字符串显示出来.

>>>from string import Template
>>>s = Template('There are ${howmany} ${lang} Qutotation Symbols')
>>>print s.substitute(lang='Python',howmany=3)
There are 3 Python Qutotation Symbols

 

>>>print s.safe_substitute(lang='Python')

There are ${howmany} Python QuotationSymbols

 

 

 

本文内容摘抄自《python核心编程第二版》page:179。

主要用作博主记录觉得比较少见的知识点,可供才考,不喜无论。

posted @ 2016-12-22 11:54  Jerry-lin  阅读(227)  评论(0编辑  收藏  举报