格式化在i中有额外花括号的字符串

2024-05-19 15:40:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个LaTeX文件,我想用Python 3读入并将一个值格式化为结果字符串。类似于:

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

但是,我还没有弄清楚如何做到这一点,因为字符串格式化的新方法使用了{val}符号,而且因为它是一个乳胶文档,所以有大量额外的{}字符。

我试过这样的方法:

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

但我知道

KeyError: 'This and that'

Tags: and文件方法字符串文档thatherevalue
1条回答
网友
1楼 · 发布于 2024-05-19 15:40:29

方法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:添加额外的大括号。可以使用regexp完成此操作。

>>> 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。我自己没有理由这么做,所以我对细节的了解不够。

相关问题 更多 >