下面是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
但是,如果我用下划线替换正斜杠,那么它工作正常。 通过附加反斜杠转义正斜杠也无济于事。
请您参考如下方法:
根据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'
