Append string variable to LaTeX based raw string

Question:

Trying to append an integer as per this post and this post.

Requirement:

from IPython.display import display, Markdown
N = 128
text = r'$QFT=frac{1}{sqrt{'+str(N)+'}} begin{bmatrix}'

text = text + r'1 & 2 \ 3 & 4 \'
text = text + r' end{bmatrix}$'
display(Markdown(text))

Tried: IndexError: Replacement index 1 out of range for positional args tuple

N = str(128)
text = r'$QFT=frac{1}{sqrt{N}} begin{bmatrix}'.format(N)

But either of these don’t work. Note, here text is LaTeX based string.

Asked By: Rajesh Swarnkar

||

Answers:

Double each curly bracket if it’s a part of the string:

> N = 128
> text = r"$QFT = frac{{1}}{{sqrt{{{0}}}}} begin{{bmatrix}}".format(N)
> print(text)
$SQFT = frac{1}{sqrt{128} begin{bmatrix}

In case you want to use a parameter N in the string, then use the explicit parameter format(N=N) to get the same effect:

> text = r"$QFT = frac{{1}}{{sqrt{{{N}}}}} begin{{bmatrix}}".format(N=N)
> print(text)
$SQFT = frac{1}{sqrt{128} begin{bmatrix}
Answered By: Celdor
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.