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
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 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.
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.
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}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With