python - 格式化其中包含额外花括号的字符串

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

我有一个 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/

相关文章:

python - Snakemake:在 Expand() 中使用正则表达式

c++ - 在 C++ 中从 cin 按下 ESC 按钮之前如何读取

bash - 如何在 bash 中转义用户输入变量中的正斜杠?

python - 将 tf.Dataset 拆分为测试和验证子集的规范方法是什么?

python - Pylint:通过脚本获取输出,类似于 pylint 可执行文件

json - 在Python中,如何简洁地替换json数据中的嵌套值?

python - 项目之间的 pytest 重用固定装置

python下载速度极慢

python - OpenCV 从 Blob 检测返回关键点坐标和面积,Python

html - 使用变量时危险地 react SetInnerHTML 不起作用