Python 格式化包含额外大括号的字符串
我有一个LaTeX文件,我想用Python3读入,并将一个值格式化为结果字符串。比如:Python 格式化包含额外大括号的字符串,python,escaping,python-3.x,string-formatting,Python,Escaping,Python 3.x,String Formatting,我有一个LaTeX文件,我想用Python3读入,并将一个值格式化为结果字符串。比如: ... \textbf{REPLACE VALUE HERE} ... '\textbf{This and that} plus \textbf{{val}}'.format(val='6') 但是我还没有弄明白如何做到这一点,因为新的字符串格式化方法使用了{val}符号,而且它是一个LaTeX文档,因此有大量额外的{}字符 我试过这样的方法: ... \textbf{REPLACE VALUE HERE
...
\textbf{REPLACE VALUE HERE}
...
'\textbf{This and that} plus \textbf{{val}}'.format(val='6')
但是我还没有弄明白如何做到这一点,因为新的字符串格式化方法使用了{val}
符号,而且它是一个LaTeX文档,因此有大量额外的{}
字符
我试过这样的方法:
...
\textbf{REPLACE VALUE HERE}
...
'\textbf{This and that} plus \textbf{{val}}'.format(val='6')
但我明白了
KeyError: 'This and that'
方法1,这就是我实际要做的:使用a 方法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}'
>>r'\textbf{This and that}加上\textbf{val}'。格式(val='6')
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
KeyError:'这个和那个'
>>>r'\textbf{{This and that}}加上\textbf{{{{val}}}.格式(val='6')
“\\textbf{This and that}加上\\textbf{6}”
(可能)方法3:使用自定义string.Formatter。我自己没有理由这样做,所以我不知道足够的细节来提供帮助。有没有线索表明string.Template将来是否会被弃用?新的Python3{}格式似乎包括这一点。对于LaTeX编辑,模板要方便得多。@levesque:从(待定)3.4开始,它还没有被弃用,它提供了与
{}
格式本身不同的功能,所以我认为它会持续一段时间。添加额外大括号而不是使用正则表达式的更好方法可能是使用str.translate
unformoint=str.maketrans({{{':'{{','}:'}}}}})
,然后要修复给定字符串,goodstring=badstring.translate(unformoint)
(注意:问题是关于Python 3.x;在2.x上,这只适用于unicode
,而不是str
,因为只有unicode
支持1-n转换映射。)