Any way to use variable values in a string literal?

Viewed 1828

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.

4 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 %%.

If your goal is to not break up the string you could do this to replace the variable with your variable value and also be able to use %s in your string:

r"What is the domain of the function $\exp{-1/(VARIABLE - x^2+y^2)}$?".replace("VARIABLE", str(VARIABLE))

If you need multiple values you can use this:

variable_list = [2, 3]
''.join([e+str(variable_list[c]) if c<len(variable_list) else str(e) for c,e in enumerate(r"What is the domain of the function $\exp{-1/(VARIABLE - x^2+y^2)}$?".split("VARIABLE"))])

You may be able to use the % formatting

variable = 10
"What is the domain of the function $exp{-1/x + %d}." % (variable)

I'm very partial to f-strings, since the variable names appear where the values eventually will.

You can have raw f-strings, but you'll need to escape curly braces by doubling them ({{), which could get confusing if you're writing out complex LaTex.

To get the string What is ... $\exp{-1/(10 - x^2+y^2)}$?:

VARIABLE = 10
rf"What is ... $\exp{{-1/({VARIABLE} - x^2+y^2)}}$?"
Related