在Python 3中格式化LaTeX数学字符串 [英] Format a LaTeX math string in Python 3
问题描述
我看到可以通过使用双大括号在python中的LaTeX字符串上使用format方法,如下所示: 但是如何在数学LaTeX字符串中使用format方法?(尤其是下标) 例如,使用: 我希望: 但是我得到一个 为清楚起见,这里有一个插图: 说明: I see it is possible to use the format method on a LaTeX string in python by using a double curly bracket as shown here. For instance: But how can I use the format method in a math LaTeX string? (particularly for subscripts) For example, with: I would expect: But I get a
The correct statement for Here's an illustration for clarity: Explanation:
The problem with
这篇关于在Python 3中格式化LaTeX数学字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
In [2]:r'$ f_ {in,{{0}}} $'.format('a')
Out [2]:"$ f_ {in,a} $"
ValueError:字段名称中出现意外的"{"
In [2]
的正确语句应为:
r'$ f _ {{in,{0}}} $'.format('a')#给出'$ f_ {in,a} $'
'$ f _ {{in,{0}}} $'.format('in')^^ _________ ^^^这些花括号被转义,从而在中间留下'in,{0}'
r'$ f_ {in,{{0}}} $'.format('a')
的问题是 $之后的花括号
和 {
f _ $
前面的花括号}
也需要转义,这就是导致 ValueError
的原因.>
要进一步了解,请在 In [1]
,'中使用同一组花括号(用
也被转义了.减少此开销时,您会注意到在这些花括号中留有 f _
括起来)f _ {{{{0}}}'.format('in') {0}
,这允许替换'in'
.因此,我们对只需在 Out [1]
中输入 f_ {in}
.为了清楚起见,下面是一个示例:
'f _ {{{0}}}'.format('in')^^ _____ ^^这些花括号被转义,从而使{0}居中#给出'f_ {in}'
In[1]: 'f_{{{0}}}'.format('in')
Out[1]: 'f_{in}'
In[2]: r'$f_{in,{{0}}}$'.format('a')
Out[2]: '$f_{in,a}$'
ValueError: unexpected '{' in field name
In[2]
should be:r'$f_{{in,{0}}}$'.format('a')
# gives '$f_{in,a}$'
'$f_{{ in, {0} }}$'.format('in')
^^_________^^
these curly braces are escaped, which leaves 'in, {0}' at the center
r'$f_{in,{{0}}}$'.format('a')
was that the curly brace {
following $f_
, and the curly brace }
preceding $
needed to be escaped as well, which is what caused the ValueError
.
To understand this further, the same set of curly braces (that f_
encloses) of the statement in In[1]
, 'f_{{{0}}}'.format('in')
, was also escaped. When you reduce this, you'll notice that {0}
is left within these set of curly braces which allows for 'in'
to be substituted in. Therefore, we evaluated to simply a f_{in}
in Out[1]
. Here's an illustration for clarity:'f_{{ {0} }}'.format('in')
^^_____^^
these curly braces are escaped, which leaves {0} at the center
# gives 'f_{in}'