格式化包含多余大括号的字符串

18 投票
1 回答
9148 浏览
提问于 2025-04-17 12:25

我有一个LaTeX文件,想用Python 3来读取,并把一个值格式化成结果字符串。大概是这样的:

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

但是我一直搞不明白怎么做,因为现在字符串格式化的新方式是用{val}这种写法,而我的LaTeX文档里面有很多额外的{}字符。

我试过类似这样的:

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

但是我得到的是

KeyError: 'This and that'

1 个回答

25

方法一,其实我会这样做:使用一个叫做 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}'

方法二:加上额外的花括号。可以用正则表达式来实现这个。

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

(可能的)方法三:使用自定义的 string.Formatter。我自己还没有遇到过这种情况,所以对细节了解得不够,没法提供太多帮助。

撰写回答