Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to use variable values in a string literal?

Tags:

python

string

I'm using python to generate LaTeX code (long story - I need to produce 120-odd unique exams).

This means that I have lots of strings that have \ or { or } etc. So I'm making them literals. However, I also want to have Python calculate numbers and put them in. So I might have a string like: r"What is the domain of the function $\exp{-1/(VARIABLE - x^2+y^2)}$?" which I want to write to a file. But I want VARIABLE to be a random numerical value. The question isn't how to calculate VARIABLE, but rather is there a clean way to put VARIABLE into the string, without something like: r"What is the domain of the function $\exp{-1/(" + str(VARIABLE) + r"- x^2+y^2)}$?"

I'm going to be doing this a lot, so if it's doable, that would be great. I've got Python 3.5.2.

like image 724
Joel Avatar asked Nov 04 '25 16:11

Joel


1 Answers

Python still supports the string substitution operator %:

r"What is ... $\exp{-1/(%s - x^2+y^2)}$?" % str(VARIABLE)

You can be more specific if you know the type of the variable, e.g.:

r"What is ... $\exp{-1/(%f - x^2+y^2)}$?" % VARIABLE

More than one variable can be substituted at once:

r"$\mathrm{x}^{%i}_{%i}$" % (VAR1, VAR2)

This will work as long as your strings do not have LaTeX comments that, incidentally, also begin with a %. If that's the case, replace % with %%.

like image 106
DYZ Avatar answered Nov 06 '25 07:11

DYZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!