在Python 3中格式化LaTeX数学字符串 [英] Format a LaTeX math string in Python 3

查看:37
本文介绍了在Python 3中格式化LaTeX数学字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到可以通过使用双大括号在python中的LaTeX字符串上使用format方法,如下所示:

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

例如,使用:

  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}' 

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

解决方案

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}'

这篇关于在Python 3中格式化LaTeX数学字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆