我有一个 LaTeX 文件,我想用 Python 3 读入并将值格式化为结果字符串。像这样的东西:
...
\textbf{REPLACE VALUE HERE}
...
但我一直无法弄清楚如何做到这一点,因为进行字符串格式化的新方法使用 {val}<
表示法,并且由于它是一个 LaTeX 文档,所以有大量额外的 {}
个字符。
我试过类似的方法:
'\textbf{This and that} plus \textbf{{val}}'.format(val='6')
但是我明白了
KeyError: 'This and that'
最佳答案
方法 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}'
方法二:添加额外的大括号。可以使用正则表达式来做到这一点。
>>> 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。我自己没有理由这样做,所以我对细节了解不够,无法提供帮助。
关于python - 格式化其中包含额外花括号的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9161355/