Gabriel Gabriel - 6 months ago 12x
Python Question

Python combining the format method with long strings that use LaTeX

I'm trying to write a long string with several LaTeX commands and variables to an image. I'm having trouble setting an arbitrary precision for the variables while maintaining the LaTeX formatting.

Here's a MWE:

import matplotlib.pyplot as plt
# Define some variables names and values.
xn, yn, cod, prec, prec2 = 'r', 'p', 'abc', 2, 4
ccl = [546.35642, 6785.35416]
ect = [12.5235, 13.643241]


text1 = "${}_{t} = {:.{p}f} \pm {:.{p}f} {c}$".format(xn, ccl[0], ect[0], c=cod, p=prec)
text2 = "${}_{t} = {:.{p}f} \pm {:.{p}f} {c}$".format(yn, ccl[1], ect[1], c=cod, p=prec2)

text = text1 + '\n' + text2
plt.text(0.5, 0.5, text)
plt.savefig('format_test.png', dpi=150)

This throws the error
KeyError: 't'
since it is recognizing the sub-index
as a variable. If instead I use:

text1 = "${{{a}}}_{t} = {:.{p}f} \pm {:.{p}f} {c}$".format(a=xn, ccl[0], ect[0], c=cod, p=prec)
text2 = "${{{a}}}_{t} = {:.{p}f} \pm {:.{p}f} {c}$".format(b=yn, ccl[1], ect[1], c=cod, p=prec2)

I get
SyntaxError: non-keyword arg after keyword arg
since now I have the
ccl[0], ect[0]
variables in
defined after
(same for the second text line).

Notice the
values at the end of
which determines the number of decimal places the number will have when printed. I need to pass this variable because it is not fixed, I can't just set a fixed value to replace

How can I make these string lines work while keeping the LaTeX formatting and the different precision needed?

tom tom

I think you need an extra curly brace around the t. This works for me:

text1 = r"${}_{{t}} = {:.{p}f} \pm {:.{p}f} {c}$".format(xn, ccl[0], ect[0], c=cod, p=prec)
text2 = r"${}_{{t}} = {:.{p}f} \pm {:.{p}f} {c}$".format(yn, ccl[1], ect[1], c=cod, p=prec2)

Adding the double curly brace means they are treated literally, not as a part of the python format syntax

enter image description here