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))

2 Answers 2

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))

Sign up to request clarification or add additional context in comments.

Comments

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'

1 Comment

Thanks for this idea. I implemented similar idea answered below and worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.