使用百分比delimi的Python字符串模板

2024-05-23 13:31:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试学习字符串模板模块,并面临使用替代分隔符时出现的问题。在

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具有前缀为%的变量名,它不起作用。在

^{pr2}$

看起来像是打字错误,我无法破解。在

string.Template可以用来替换%变量吗?在


Tags: sample字符串textstringisa1templateval
1条回答
网友
1楼 · 发布于 2024-05-23 13:31:45

您从模板创建了一个模板

>>> temp_text_amp = string.Template(" This is a sample text %a1 %a3 ")
[...]
>>> t2 = MyTemplate(temp_text_amp)

temp_text_amp不是字符串。这就是你看到的回溯的原因。在

改为从字符串创建模板对象:

^{pr2}$

下一个问题是您将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 '

相关问题 更多 >