【发布时间】:2014-06-23 10:07:51
【问题描述】:
我正在尝试学习字符串模板模块并使用替代分隔符面临打嗝。
temp_text_dollar 具有以$ 为前缀的变量名,并且工作正常
>>> import string
>>> val = {'a1':'VAL1' , 'a2' : 'VAL2' , 'a3' : 'VAL3' , 'a4' : 'VAL4' }
>>> temp_text_dollar = string.Template(" This is a sample text ${a1} $a3 ")
>>> print temp_text_dollar.substitute(val)
This is a sample text VAL1 VAL3
>>> print temp_text_dollar.delimiter
$
>>> print temp_text_dollar.idpattern
[_a-z][_a-z0-9]*
>>> print temp_text_dollar.template
This is a sample text ${a1} $a3
temp_text_pct 有以% 为前缀的变量名,但它不起作用。
>>> temp_text_pct = string.Template(" This is a sample text %a1 %a3 ")
>>> class MyTemplate(string.Template):
... delimiter = '%'
... idpattern = '[a-z]*'
...
>>> t2 = MyTemplate(temp_text_pct)
>>> print t2.substitute(val)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/string.py", line 172, in substitute
return self.pattern.sub(convert, self.template)
TypeError: expected string or buffer
>>> print t2.delimiter
%
>>> print t2.idpattern
[a-z]*
看起来像是拼写错误,我无法破解它。
string.Template 可以用来代替% 变量吗?
【问题讨论】:
标签: python templates python-2.7