Python文字列テンプレート


新しい文字列Templateオブジェクトの導入によりstringモジュールが再活性化され,Templateオブジェクトには2つの方法があり,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 "", 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