Search code examples
python-3.xvisual-studio-codemarkdownkatex

IPython.display.Markdown does not render KaTeX correctly


When trying to display a mathematical equation, it seems as if KaTeX only considers the first letter following a \ when rendering the equation. Here is an example:

from IPython.display import Markdown as md
display(md("$ \frac{1}{2}) $"))

ParseError: KaTeX parse error: Unexpected character: '' at position 1: ̲rac{1}{2})

I'm using Python 3.9 in VS Code


Solution

  • Try putting an r before your string. Your string will be considered a so called raw string and the backslash will not escape the f character.

    This should work

    from IPython.display import Markdown as md
    display(md(r"$ \frac{1}{2}) $"))
    

    The backslash is used to form so-called escape characters when used together with another character. In your case it seems like KaTeX had trouble to interpret the \f (or 'form feed') character.