43

I was writing a very simple script to count ellipsoid area and volume and some other things. I was presenting my output printing it out like this:

print('Dims: {}x{}m\nArea: {}m^2\nVolume: {}m^3'.format(a, round(b,2), P, V))

What, of course, gave this output (with sample data):

Dims: 13.49x2.25m
Area: 302.99m^2
Volume: 90.92m^3

As I wrote earlier, I am using jupyter notebook, so I can use $ operators in markdown cells to create LaTeX formulas.

My question is, is it possible to generate output using Python code in a way that it will be understood as LaTeX formula and printed in such a way, that:

Latex_example

Thanks for all replies.

sophros
  • 14,672
  • 11
  • 46
  • 75
Sqoshu
  • 944
  • 2
  • 9
  • 16

3 Answers3

42

Use IPython.display's display function with a Math object:

from IPython.display import display, Math
display(Math(r'Dims: {}x{}m \\ Area: {}m^2 \\ Volume: {}m^3'.format(a, round(b,2), P, V)))

Note the use of Latex-style \\ newlines, and the r'' string, which will take the backslashes as literal backslashes and not see them as escape characters.

Found the solution here.

sebas
  • 1,283
  • 1
  • 12
  • 16
  • 1
    Indeed works, thanks for the answer. Didn't even expect that it can be so intuitive and easy. – Sqoshu Mar 09 '18 at 09:50
16

Here's another solution that let's you include text and math a little easier: Use Markdown with r (so backslashed don't become escape chars) and f string for value insertion.

from IPython.display import display, Markdown

a = 13.49
b = 2.2544223
P = 302.99
V = 90.02

display(Markdown(
   rf"""
Dims: ${a}m \times{b:5.2}m$

Area: ${P}m^2$

Volume: ${V}m^3$
"""))
JMann
  • 579
  • 4
  • 12
  • 4
    Watch out for curly latex brackets and f-strings! e.g. `rf'Dims: ${13.49}m \times{2.2544:5.2}\sqrt{Hz}$'` needs to be `rf'Dims: ${13.49}m \times{2.2544:5.2}'r'\sqrt{Hz}$'`. :) – Aaron Jan 06 '20 at 15:55
  • Backslashes don't seem to be allowed in f strings at all – Alexander Wu Aug 21 '21 at 04:28
  • @AlexanderWu: Yes, that is true ... in general, but not with the usual grammar in `print(rf'...')`, "r" for _raw_ string interpretation. Additionally when`Markdown` is invoked using `display(Markdown(rf'... $...$ ... ')) there is no need to escape whatever backslash is in between the dollar signs because they are interpreted literally as part of the Markdown syntax. You can pretty much embed usual Markdown content formatting in there. – Cbhihe Nov 25 '22 at 10:45
1

(don't have enough reputation to comment on the discussion below JMann's answer)

To escape LaTeX curly braces in format strings, you can double up the curly braces. e.g.

rf"NEP $\Nu_{{photon}}$: {calc_nep(T):.3f} $\frac{{W}}{{ \sqrt{{Hz}} }}$."