我正在尝试学习字符串模板模块并使用替代分隔符来面对打嗝。
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
可以用来替换%
变量吗?
答案 0 :(得分:3)
您是从模板创建模板:
>>> temp_text_amp = string.Template(" This is a sample text %a1 %a3 ")
[...]
>>> t2 = MyTemplate(temp_text_amp)
temp_text_amp
不是字符串。这就是导致你看到的追溯的原因。
从字符串创建模板对象:
t2 = MyTemplate(" This is a sample text %a1 %a3 ")
您的下一个问题是,您将idpattern
限制为只是字母:
idpattern = '[a-z]*'
但您的实际模板字符串也使用数字。
这很好用:
>>> import string
>>> class MyTemplate(string.Template):
... delimiter = '%'
... idpattern = '[a-z0-9]*'
...
>>> t2 = MyTemplate(" This is a sample text %a1 %a3 ")
>>> val = {'a1':'VAL1' , 'a2' : 'VAL2' , 'a3' : 'VAL3' , 'a4' : 'VAL4' }
>>> t2.substitute(val)
' This is a sample text VAL1 VAL3 '