1

I am trying to write a LaTex from a Python script:

n=4
content = r'''\documentclass{article}

\begin{document}
the value of "n" is n
\end{document}
'''

How could I read the value of n inside of the command r''' '''?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Don P.
  • 25
  • 3
  • Does this answer your question? [Can you have variables within triple quotes? If so, how?](https://stackoverflow.com/questions/3877623/can-you-have-variables-within-triple-quotes-if-so-how) – mkrieger1 Aug 01 '22 at 21:08

1 Answers1

3

You can use the fstring formating: This is probably the easiest and recommended method.

For example:

n=4
content = rf'''\documentclass{{article}}

\begin{{document}}
the value of "n" is {n}
\end{{document}}
'''
print(content)

There is also the .format() method

n=4
content = r'''\documentclass{{article}}

\begin{{document}}
the value of "n" is {0}
\end{{document}}
'''
content.format(n)
print(content)

There is the printf style formatting.

n=4
content = r'''\documentclass{article}

\begin{document}
the value of "n" is %d
\end{document}
''' % n
print(content)

You can also concatenate different string sections together

n=4
content = r'''\documentclass{article}

\begin{document}
the value of "n" is ''' + str(n) + ''' 
\end{document}
'''
print(content)
Alexander
  • 16,091
  • 5
  • 13
  • 29