Skip to main content
 首页 » 编程设计

Python string.Template 去除double $

2025年05月04日15mate10pro

我正在使用 string.Template.safe_substitute(...) 用给定的字典替换字符串中的键。这些字符串可能包含双 $ 字符,我不想将其替换,因为它们不是键。

给定以下示例:

>>> Template("foo$$bar").safe_substitute({"key":"val"}) 
'foo$bar' 

我实际上希望字符串不会更改,因为字典中的 key 与给定字符串中的任何 $key 都不匹配,并且该函数的文档说:

the original placeholder will appear in the resulting string intact. Also, unlike with substitute(), any other appearances of the $ will simply return $ instead of raising ValueError.

但是 $ 中的一个被删除了。这是为什么?

请您参考如下方法:

作为documentation说:

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

如果你想保留 2 $ 你需要转义它两次:

>>> Template("foo$$$$bar").safe_substitute({"key":"val"}) 
'foo$$bar'