格式化一个包含额外花括号的字符串

Kei*_*son 15 python escaping string-formatting python-3.x

我有一个我想用Python 3读取的LaTeX文件,并将值格式化为结果字符串.就像是:

...
\textbf{REPLACE VALUE HERE}
...
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何做到这一点,因为新的字符串格式化方法使用{val}符号,因为它是一个LaTeX文档,有大量的额外{}字符.

我尝试过类似的东西:

'\textbf{This and that} plus \textbf{{val}}'.format(val='6')
Run Code Online (Sandbox Code Playgroud)

但我明白了

KeyError: 'This and that'
Run Code Online (Sandbox Code Playgroud)

DSM*_*DSM 22

方法1,这是我实际做的:改为使用string.Template.

>>> from string import Template
>>> Template(r'\textbf{This and that} plus \textbf{$val}').substitute(val='6')
'\\textbf{This and that} plus \\textbf{6}'
Run Code Online (Sandbox Code Playgroud)

方法2:添加额外的大括号.可以使用正则表达式执行此操作.

>>> r'\textbf{This and that} plus \textbf{val}'.format(val='6')
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
KeyError: 'This and that'
>>> r'\textbf{{This and that}} plus \textbf{{{val}}}'.format(val='6')
'\\textbf{This and that} plus \\textbf{6}'
Run Code Online (Sandbox Code Playgroud)

(可能)方法3:使用自定义string.Formatter.我自己没有理由这样做,所以我不知道足够的细节是否有用.