Python字符串模板


由於新式的字符串Template 對象的引進使得string 模塊又重新活了過來,Template 對象有兩個方法,substitute()和safe_substitute().前者更為嚴謹,在key 缺少的情況下它會報一個KeyError 的異常出來,而后者在缺少key 時,直接原封不動的把字符串顯示出來.

>>> from string import Template
>>> s = Template('There are ${howmany} ${lang} Quotation Symbols')
>>>
>>> print s.substitute(lang='Python', howmany=3)
There are 3 Python Quotation Symbols
>>>
>>> print s.substitute(lang='Python')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/local/lib/python2.4/string.py", line 172, in substitute
return self.pattern.sub(convert, self.template)
File "/usr/local/lib/python2.4/string.py", line 162, in convert val =
mapping[named]
KeyError: 'howmany'
>>>
>>> print s.safe_substitute(lang='Python')
There are ${howmany} Python Quotation Symbols

也可以使用一個字典來作為替代key的數據結構傳入

from string import Template

s = Template('There are ${howmany} ${lang} Quotation Symbols')
repDict = {'lang' : 'Python', 'howmany' : 3}
print s.substitute(repDict) #There are 3 Python Quotation Symbols

注意!

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



 
粤ICP备14056181号  © 2014-2020 ITdaan.com