Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Append string variable to LaTeX based raw string

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading