How to add Markdown inside a function to pretty print equation

I suspect you are looking for display(Markdown(s)) to display a string defined by s, where s would include your equation with MathJax.

Here is a not quite complete implementation. Pasting it in a cell and running the code should give you output in markdown form where the markdown in based on variables in the code:

from IPython.display import Markdown, display
def printmd(string):
    display(Markdown(string))
printmd('**BOLD TEXT**')
equation_str= '$$c = \sqrt{a^2 + b^2}$$'
printmd(f'Equation:\n{equation_str}')
a = '9'
b = '12'
import math
c = math.sqrt(int(a)**2 + int(b)**2)
equation_str = equation_str.replace('a',a).replace('b',b).replace('c',str(c))
printmd(f'Equation using assigned variables:\n{equation_str}')

(Based on the answer here and extending that to including an equation to render in markdown.)

There is an extension, Python Markdown, that would allow you to mix in Python variables in markdown cells. You’ll note under ‘Further examples’ there that it allows mixing in of LaTeX/MathJax syntax. This post talks about using that extension and sympy to do pretty printing.
(Use of the Python Markdown extension and display(Markdown(s)) are also discussed here.)

3 Likes