Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print math symbols (using latex) like sigma with f-strings?

x = np.array([5,4,3])
y = np.array([1,2,3])
print(f"{sum(x*y)}, {sum(x**2)}, {sum(y**2)}")
#> 22, 50, 14

I want to print with the mathematical symbols displayed
\sum{x*y}

But when I use f-string

print(f"$\sum{xy}$ = {sum(x*y)}, $\sum{x^2}$ = {sum(x**2)}, , $\sum{y^2}$ = {sum(y**2)}")

I get error: NameError: name 'xy' is not defined. Seems like f-strings are not able to recognize latex code.

What's the solution here?

like image 887
rahul-ahuja Avatar asked Nov 29 '25 18:11

rahul-ahuja


1 Answers

tl;dr: python can't print LaTex to terminal.

Usually, terminals are text only. That means that special LaTeX images cannot be displayed.

However, there are some ways that you can still view LaTeX (though not through terminal).

For example, you can call pdflatex through terminal (assuming you have it installed)

import os

latex = "Insert Latex Code here"
with open("latex.tex", "w") as file:
    file.write(latex)

os.system("pdflatex latex.tex")

Your LaTeX should be rendered as a pdf called latex.pdf

like image 61
jeffarjeffar Avatar answered Dec 02 '25 08:12

jeffarjeffar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!