Python字符串模板

2024-06-26 02:21:15 发布

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

我们使用字符串模板通过提供dict替换Python字符串中的一些值。它工作得很好。然而,尽管使用了safe_替换,下面的代码并没有如预期的那样工作。知道为什么吗?在

from string import Template 
obj = Template("$$Tag$$") 
obj.safe_substitute({}) 

Output : '$Tag$' Expected : '$$Tag$$' 
(As there is no value to replace in the dict supplied .)

如果我将“########################。有人知道为什么它忽略了一个额外的分隔符吗?只是想弄清楚到底发生了什么。在


Tags: 字符串代码fromimport模板objoutputstring
3条回答

您必须在输出中为每一个输入两个美元符号:

>>> Template('$$$$Tag$$$$').substitute()
'$$Tag$$'

来自docs

$$ is an escape; it is replaced with a single $.

如果您想要双$,那么您可以使用如下内容:

>>> obj = Template("$$$$Tag$$$$")
>>> obj.safe_substitute({})
'$$Tag$$'
>>> obj.safe_substitute({'Tag':1})
'$$Tag$$'
>>> obj = Template("$$$Tag$$$") #First $ escapes the second $
>>> obj.safe_substitute({'Tag':1})
'$1$$'

从文件中:

"$$" is an escape; it is replaced with a single "$".

相关问题 更多 >