Python中Template是string中的一個類,可以將字符串的格式固定下來,重復利用。
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
用法很簡單,先生成一個模板實例s,然后調用替換函數substitute()將模板中的兩個地方替換掉。替換的內容是通過字典對調用的,所以下面(lang='Python',howmany=3)出現的順序可以不用嚴格的和模板中的一樣。當然不用括號也是可以的。
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
注意:在使用${howmany} ${lang}時候,括號里的內容和括號要緊貼着,不然會報錯。
from string import Template
s = Template("there are ${ howmany } ${lang} Quotation symbols")
print s.substitute(lang='Python',howmany=3)
>>>Traceback (most recent call last):
File "E:/�������/201703/DeepLearning/neural-networks-and-deep-learning-master/src/validation.py", line 39, in <module>
print s.substitute(lang='Python',howmany=3)
File "C:\Users\wangxin\Anaconda2\lib\string.py", line 176, in substitute
return self.pattern.sub(convert, self.template)
File "C:\Users\wangxin\Anaconda2\lib\string.py", line 173, in convert
self._invalid(mo)
File "C:\Users\wangxin\Anaconda2\lib\string.py", line 146, in _invalid
(lineno, colno))
ValueError: Invalid placeholder in string: line 1, col 11
當然在使用substitute()的時候,對應的關鍵字和值都要給出,不然會報錯。
from string import Template s = Template("there are ${ howmany } ${lang} Quotation symbols") print s.substitute(lang='Python') >>>Traceback (most recent call last): File "E:/�������/201703/DeepLearning/neural-networks-and-deep-learning-master/src/validation.py", line 39, in <module> print s.substitute(lang='Python') File "C:\Users\wangxin\Anaconda2\lib\string.py", line 176, in substitute return self.pattern.sub(convert, self.template) File "C:\Users\wangxin\Anaconda2\lib\string.py", line 166, in convert val = mapping[named] KeyError: 'howmany'
使用safe_substitute()可以避免報錯.
from string import Template s = Template("there are ${howmany} ${lang} Quotation symbols") print s.safe_substitute(lang='Python') >>>there are ${howmany} Python Quotation symbols