我正在尝试使用科学记数法将数字格式设置为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:**或pow()不支持的操作数类型:'str'和'int'
答案 0 :(得分:2)
这是一个简单的解决方案:
def SuperScriptinate(number):
return number.replace('0','⁰').replace('1','¹').replace('2','²').replace('3','³').replace('4','⁴').replace('5','⁵').replace('6','⁶').replace('7','⁷').replace('8','⁸').replace('9','⁹').replace('-','⁻')
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^" + SuperScriptinate(str(b))
答案 1 :(得分:0)
我认为您的主要问题是how can the caret-exponent be replaced with a superscript?
如果您在Jupyter笔记本中使用python,有一种简单的方法:
from IPython.display import display, Math, Latex
# if the number is in scientific format already
display(Math('2.14e-6'.replace('e', r'\times 10^{') + '}'))
# if it is not:
d = "%e" % (number)
# then use the above form: display(Math(d.replace('e', r'\times ...