1

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.

Rajesh Swarnkar
  • 601
  • 1
  • 6
  • 18
  • take a look at https://stackoverflow.com/questions/5466451/how-do-i-print-curly-brace-characters-in-a-string-while-using-format, in your case that probably should look something like ` r'$QFT=\frac{{1}}{{\sqrt{{{N}}}}} \begin{{bmatrix}}'.format(N=N)` – aleksandarbos Nov 07 '22 at 13:35
  • `text = r'$QFT=\frac{{1}}{{\sqrt{{N}}}}\begin{{bmatrix}}'.format(N)` This renders the LaTeX well but its not replacing the `N` by value `128`. – Rajesh Swarnkar Nov 07 '22 at 13:40
  • 1
    in your statement you posted in the comment above you're missing extra `{}` around `N` and you need to specify `.format(N=N)` because the formatting function doesn't know which placeholder it should fill in. – aleksandarbos Nov 07 '22 at 13:45

1 Answers1

1

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}
Celdor
  • 2,437
  • 2
  • 23
  • 44