Format a LaTeX math string in Python 3

无人久伴 提交于 2021-02-08 17:10:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!