Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a LaTeX math string in Python 3

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
like image 968
Daniel Avatar asked Jan 18 '18 02:01

Daniel


People also ask

How do you use %d and %s in Python?

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.

What is %d of %D in Python?

What does %d do in Python? The %d operator is used as a placeholder to specify integer values, decimals, or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified.

How do I format a string to print in Python?

There are several ways to format output. To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark. Inside this string, you can write a Python expression between { and } characters that can refer to variables or literal values.


1 Answers

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}'
like image 87
NatKSS Avatar answered Oct 11 '22 18:10

NatKSS