格式化一个字符串,其中包含额外的花括号 [英] Format a string that has extra curly braces in it
问题描述
...
\textbf {REPLACE VALUE HERE}
...
但是,由于使用新的字符串格式化方式,我无法弄清楚如何做到这一点 {val}
符号,由于它是一个LaTeX文档,有大量额外的 {}
字符。
我尝试过如下:
'\textbf {那个}加\textbf {{val}}'。format(val ='6')
但是我得到
KeyError:'这个和'
方法1,这是我实际做的:使用 string.Template 。
> >>从字符串导入模板
>>> Template(r'\textbf {This and that} plus \textbf {$ val}')。substitute(val ='6')
'\\textbf {This and that}加\\\ \\ textbf {6}'
方法2:添加额外的大括号。可以使用正则表达式执行此操作。
>>> r'\textbf {This and that}加\textbf {val}'。format(val ='6')
追溯(最近的最后一次调用):
文件< interactive input> ,第1行在< module>
KeyError:'这个和'
>>> r'\textbf {{This and that}}加\textbf {{{val}}}'。format(val ='6')
'\\textbf {This and that} plus \\ \\\textbf {6}'
(可能)方法3:使用自定义string.Formatter。我没有理由自己做,所以我不知道足够的细节是有帮助的。
I have a LaTeX file I want to read in with Python 3 and format a value into the resultant string. Something like:
...
\textbf{REPLACE VALUE HERE}
...
But I have not been able to figure out how to do this since the new way of doing string formatting uses {val}
notation and since it is a LaTeX document, there are tons of extra {}
characters.
I've tried something like:
'\textbf{This and that} plus \textbf{{val}}'.format(val='6')
but I get
KeyError: 'This and that'
Method 1, which is what I'd actually do: use a string.Template instead.
>>> from string import Template
>>> Template(r'\textbf{This and that} plus \textbf{$val}').substitute(val='6')
'\\textbf{This and that} plus \\textbf{6}'
Method 2: add extra braces. Could do this using a 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}'
(possible) Method 3: use a custom string.Formatter. I haven't had cause to do this myself so I don't know enough of the details to be helpful.
这篇关于格式化一个字符串,其中包含额外的花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!