简体   繁体   English

如何使用 f 字符串打印数学符号(使用乳胶),如 sigma?

[英]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我想打印显示的数学符号
\和{x*y}

But when I use f-string但是当我使用 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 .我收到错误: NameError: name 'xy' is not defined Seems like f-strings are not able to recognize latex code.似乎 f 字符串无法识别 latex 代码。

What's the solution here?这里有什么解决方案?

I'm not sure I understood your question correctly, but the reason for the error is that Python recognizes the curly braces in your latex code and tries to format it as usual in the f-String, therefore not finding the xy variable, as it doesn't exist.我不确定我是否正确理解了您的问题,但错误的原因是 Python 识别您的 latex 代码中的花括号并尝试在 f-String 中像往常一样对其进行格式化,因此找不到xy变量,因为它不存在。

You have to escape the latex braces using double braces:您必须使用双大括号转义 Z25F7E525B5C0641E1EB1FB3BDEBEB15B5Z 大括号:

print(f"$\sum{{xy}}$ = {sum(x*y)}, and so on...”)

tl;dr: python can't print LaTex to terminal. tl;博士:python 无法将 LaTex 打印到终端。

Usually, terminals are text only.通常,终端只是文本。 That means that special LaTeX images cannot be displayed.这意味着无法显示特殊的 LaTeX 图像。

However, there are some ways that you can still view LaTeX (though not through terminal).但是,您仍然可以通过某些方式查看 LaTeX(虽然不是通过终端)。

For example, you can call pdflatex through terminal (assuming you have it installed)例如,您可以通过终端调用pdflatex (假设您已经安装了它)

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您的 LaTeX 应呈现为 pdf,称为latex.pdf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM