在 Python 3 中格式化 LaTeX 数学字符串

Dan*_*iel 6 string math latex python-3.x

我认为有可能通过使用一个双花括号如图所示使用的格式方法上的乳胶串在python这里。例如:

In[1]: 'f_{{{0}}}'.format('in')
Out[1]: 'f_{in}'
Run Code Online (Sandbox Code Playgroud)

但是如何在数学 LaTeX 字符串中使用 format 方法?(特别是下标)

例如,与:

In[2]: r'$f_{in,{{0}}}$'.format('a')
Run Code Online (Sandbox Code Playgroud)

我希望:

Out[2]: '$f_{in,a}$'
Run Code Online (Sandbox Code Playgroud)

但我得到一个

ValueError: unexpected '{' in field name
Run Code Online (Sandbox Code Playgroud)

Nat*_*KSS 7

正确的说法In[2]应该是:

r'$f_{{in,{0}}}$'.format('a')
# gives '$f_{in,a}$'
Run Code Online (Sandbox Code Playgroud)

为了清楚起见,这里有一个插图:

'$f_{{ in, {0} }}$'.format('in')
    ^^_________^^
    these curly braces are escaped, which leaves 'in, {0}' at the center
Run Code Online (Sandbox Code Playgroud)

说明: 问题r'$f_{in,{{0}}}$'.format('a')在于{后面$f_的大括号和}前面的大括号也$需要转义,这就是导致ValueError.



要理解这一点进一步,相同的一组大括号(即中f_在声明中封闭)In[1]'f_{{{0}}}'.format('in'),也逃过一劫。当你减少这个时,你会注意到{0}留在这些花括号中,它允许'in'被替换。因此,我们评估为简单的 a f_{in}in Out[1]。为了清楚起见,这里有一个插图:

'f_{{ {0} }}'.format('in')
   ^^_____^^
     these curly braces are escaped, which leaves {0} at the center

# gives 'f_{in}'
Run Code Online (Sandbox Code Playgroud)