问题
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:
In[1]: 'f_{{{0}}}'.format('in')
Out[1]: 'f_{in}'
But how can I use the format method in a math LaTeX string? (particularly for subscripts)
For example, with:
In[2]: r'$f_{in,{{0}}}$'.format('a')
I would expect:
Out[2]: '$f_{in,a}$'
But I get a
ValueError: unexpected '{' in field name
回答1:
The correct statement for In[2]
should be:
r'$f_{{in,{0}}}$'.format('a')
# gives '$f_{in,a}$'
Here's an illustration for clarity:
'$f_{{ in, {0} }}$'.format('in')
^^_________^^
these curly braces are escaped, which leaves 'in, {0}' at the center
Explanation:
The problem with 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}'
来源:https://stackoverflow.com/questions/48313125/format-a-latex-math-string-in-python-3