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

时间:2012-02-06 14:10:27

标签: python escaping python-3.x string-formatting

我想要使用Python 3读取一个LaTeX文件,并将值格式化为结果字符串。类似的东西:

...
\textbf{REPLACE VALUE HERE}
...

但是由于新的字符串格式化方式使用{val}表示法,因此我无法弄清楚如何执行此操作,因为它是一个LaTeX文档,所以有大量额外的{}个字符

我尝试过类似的事情:

'\textbf{This and that} plus \textbf{{val}}'.format(val='6')

但我得到

KeyError: 'This and that'

1 个答案:

答案 0 :(得分:20)

方法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}'

方法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}'

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