Format number using LaTeX notation in Python(在 Python 中使用 LaTeX 表示法格式化数字)
问题描述
在 Python 中使用格式字符串,我可以轻松地以科学记数法"打印一个数字,例如
Using format strings in Python I can easily print a number in "scientific notation", e.g.
>> print '%g'%1e9
1e+09
将数字格式化为 LaTeX 格式的最简单方法是什么,即 1 imes10^{+09}?
What is the simplest way to format the number in LaTeX format, i.e. 1 imes10^{+09}?
推荐答案
siunitx LaTeX 包解决了这个问题允许您直接使用 python 浮点值,而无需解析结果字符串并将其转换为有效的 LaTeX.
The siunitx LaTeX package solves this for you by allowing you to use the python float value directly without resorting to parsing the resulting string and turning it into valid LaTeX.
>>> print "\num{{{0:.2g}}}".format(1e9)
um{1e+09}
LaTeX文档编译后,上面的代码会变成.正如 andybuckley 在评论中指出的那样,加号可能不被 siunitx 接受(我没有测试过),所以可能需要执行 .repace("+", "")
关于结果.
When the LaTeX document is compiled, the above code will be turned into
. As andybuckley points out in the comments, the plus sign might not be accepted by siunitx (I've not tested it), so it may be necessary to do a .repace("+", "")
on the result.
如果使用 siunitx
以某种方式无法解决,请编写如下自定义函数:
If using siunitx
is somehow off the table, write a custom function like this:
def latex_float(f):
float_str = "{0:.2g}".format(f)
if "e" in float_str:
base, exponent = float_str.split("e")
return r"{0} imes 10^{{{1}}}".format(base, int(exponent))
else:
return float_str
测试:
>>> latex_float(1e9)
'1 \times 10^{9}'
这篇关于在 Python 中使用 LaTeX 表示法格式化数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中使用 LaTeX 表示法格式化数字


基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01