0

I have a poorly formatted LaTeX which needs to be formatted in specific manner to render in Jupyter Notebook correctly:

# Supporting Libraries:
from qiskit.visualization import array_to_latex
from IPython.display import display, Markdown

# Unsuitable LaTeX
latex_baad =  '$QFT = \\frac{1}{\\sqrt{32}} \n\n\\begin{bmatrix}\n0  \\\\\n -1  \\\\\n \\end{bmatrix}\n \\otimes \n\n\\begin{bmatrix}\n0  \\\\\n \\tfrac{1}{\\sqrt{2}}(1 - i)  \\\\\n \\end{bmatrix}\n \\otimes \n\n\\begin{bmatrix}\n0  \\\\\n -0.92388 + 0.38268i  \\\\\n \\end{bmatrix}\n \\otimes \n\n\\begin{bmatrix}\n0  \\\\\n -0.19509 - 0.98079i  \\\\\n \\end{bmatrix}\n$'

# Suitable LaTeX
latex_good = r'$QFT =  \frac{1}{ \sqrt{32}}      \begin{bmatrix}  0  \\     -1          \end{bmatrix}    \otimes      \begin{bmatrix}  0       \\ \tfrac{1}{ \sqrt{2}}(1 - i)          \end{bmatrix}    \otimes      \begin{bmatrix}  0      \\ -0.92388 + 0.38268i          \end{bmatrix}    \otimes      \begin{bmatrix}  0      \\ -0.19509 - 0.98079i          \end{bmatrix}$'


display(Markdown(latex_good))
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Rajesh Swarnkar
  • 601
  • 1
  • 6
  • 18

2 Answers2

1

use replace to modify it in place, <your_string>.replace('substring to remove','substring to replace')

I would suggest making all "\n\n" into "\n", then all "\n" into " "

your_string.replace("\n\n","\n")
your_string.replace("\n", " ")
your_string.replace("////","//")

For raw (no escapes) I believe you just preface your string with r' '.

like:

string = r'this will ignore escape characters \n\n'

user11717481
  • 1
  • 9
  • 15
  • 25
1

This could be fixed by replacing the newlines \n with a temporary character e.g. ~ which is not present in latex_baad.


latex_baad = latex_baad.replace("\n","~")
latex_good = latex_baad.replace("~","")

display(Markdown(latex_good))

Rajesh Swarnkar
  • 601
  • 1
  • 6
  • 18