【发布时间】:2018-11-30 07:52:54
【问题描述】:
我正在尝试使用以 10 为底的指数以科学记数法格式化数字,例如使用 python 3 将 0.00123 写为 1.23x10–3。
我发现了这个打印 1.23x10^-3 的很棒的函数,但是如何将插入符号指数替换为上标呢?
def sci_notation(number, sig_fig=2):
ret_string = "{0:.{1:d}e}".format(number, sig_fig)
a,b = ret_string.split("e")
b = int(b) # removed leading "+" and strips leading zeros too.
return a + "x10^" + str(b)
print(sci_notation(0.001234, sig_fig=2)) # Outputs 1.23x10^-3
函数由https://stackoverflow.com/a/29261252/8542513修改。
我尝试将https://stackoverflow.com/a/8651690/8542513 的答案合并到上标格式,但我不确定 sympy 如何处理变量:
from sympy import pretty_print as pp, latex
from sympy.abc import a, b, n
def sci_notation(number, sig_fig=2):
ret_string = "{0:.{1:d}e}".format(number, sig_fig)
a,b = ret_string.split("e")
b = int(b) #removed leading "+" and strips leading zeros too.
b = str(b)
expr = a + "x10"**b #Here's my problem
pp(expr) # default
pp(expr, use_unicode=True)
return latex(expr)
print(latex(sci_notation(0.001234, sig_fig=2)))
返回:TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
【问题讨论】:
-
您在哪里打印?并非所有内容都支持上标(例如,控制台)
-
我想将该函数应用于熊猫数据框。 stackoverflow.com/a/8651690/8542513 的代码在 Jupyter Notebook 中打印指数。
-
它只是在不同的行中打印
n,使它看起来像一个(格式错误的)指数 -
你想要的结果是什么?你想要数字为 0.001234 还是 1.23x10^-3 。
-
我希望以 10 为底的指数作为上标(见问题的第一行)
标签: python superscript