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]
plt.figure()
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 {t}
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 format
defined after a=xn
(same for the second text line).
Notice the prec
and prec2
values at the end of format
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 {:.{p}f}
.
How can I make these string lines work while keeping the LaTeX formatting and the different precision needed?
%4d means 4 spaces and then after print and same %7.2f, but .2 indicate after point only show two values.
The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}.
If you have to concatenate sequence of strings with a delimited, then use join() function. If some formatting is also required with concatenation, then use format() function or f-string. Note that f-string can be used with Python 3.6 or above versions.
Python's str. format() method of the string class allows you to do variable substitutions and value formatting.
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
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