以下是mwe:
from string import Template
key_val = {'a/b/c': 1}
ans = Template('val of ${a/b/c}').substitute(key_val)
这会出错:
ValueError: Invalid placeholder in string: line 1, col 8
但是,如果我用下划线替换正斜杠,那么它可以正常工作。 通过附加反斜杠来逃避正斜杠也无济于事。
答案 0 :(得分:1)
根据documentation,占位符值的默认正则表达式为[_a-z][_a-z0-9]*
,这意味着不允许使用/
字符。如果你想允许这个,你应该继承Template
并重新定义idpattern
表达式:
from string import Template
class MyTemplate(Template):
idpattern = r"[_a-z][_a-z0-9/]*" # allowing forward slash
key_val = {'a/b/c': 1}
ans = MyTemplate('val of ${a/b/c}').substitute(key_val)
演示:
In [8]: from string import Template
In [9]: class MyTemplate(Template):
...: idpattern = r"[_a-z][_a-z0-9/]*" # allowing forward slash
...:
In [10]: key_val = {'a/b/c': 1}
In [11]: ans = MyTemplate('val of ${a/b/c}').substitute(key_val)
In [12]: ans
Out[12]: 'val of 1'