在Python中将2e+18转换为2x10^18
如果我这样做:在Python中将2e+18转换为2x10^18,python,python-2.7,Python,Python 2.7,如果我这样做: print("{:.0e}".format(2500000000000000000)) 然后我出去:2e+18 如何将此输出设置为2x10^18,而将指数正确上标 我知道使用ticker可以使用mathtext=True更改输出,但这似乎不适用于字符串格式 编辑:对不起,伙计们,我试图简化这个问题,因为我认为这个问题可以解决。我正在尝试对轴上的记号进行此更改: xticklabels[-1] = '{0:.0e}'.format(xticklabels[-1]).rep
print("{:.0e}".format(2500000000000000000))
然后我出去:2e+18
如何将此输出设置为2x10^18,而将指数正确上标
我知道使用ticker可以使用mathtext=True更改输出,但这似乎不适用于字符串格式
编辑:对不起,伙计们,我试图简化这个问题,因为我认为这个问题可以解决。我正在尝试对轴上的记号进行此更改:
xticklabels[-1] = '{0:.0e}'.format(xticklabels[-1]).replace('e+','x10^')
它按照@progo的建议工作,但不在指数上标 愚蠢的解决方案:
print("{0:.0e}".format(2500000000000000000).replace('e+', 'x10^'))
=> 2x10^18
TeX版本:
def to_TeX(num):
num = "{0:.0e}".format(num)
mantissa, exponent = num.split('e')
exponent = int(exponent)
return "{0} \times 10^{{{1}}}".format(mantissa, exponent)
>>> to_TeX(1.8e21)
'2 \times 10^{21}'
愚蠢的解决方案:
print("{0:.0e}".format(2500000000000000000).replace('e+', 'x10^'))
=> 2x10^18
TeX版本:
def to_TeX(num):
num = "{0:.0e}".format(num)
mantissa, exponent = num.split('e')
exponent = int(exponent)
return "{0} \times 10^{{{1}}}".format(mantissa, exponent)
>>> to_TeX(1.8e21)
'2 \times 10^{21}'
这是一个Python2/Python3解决方案
# -*- coding: utf-8 -*
try:
unicode
except:
unicode = str
_superscripts = u'⁻⁰¹²³⁴⁵⁶⁷⁸⁹'
_superscript_map = dict(zip(map(ord, u'-0123456789'), _superscripts))
def to_fancy(number, fmt='e'):
as_str = format(number, fmt)
as_str, _, exponent = as_str.partition('e')
if exponent: # will also print 10^0, add `and int(exponent)` to
# not add x10^0 at all.
exponent = unicode(int(exponent.replace('+', '')))
exponent = exponent.translate(_superscript_map)
as_str += u'×10' + exponent
return as_str
>>> print(to_fancy(0.00000000321))
3.210000×10⁻⁹
这是一个Python2/Python3解决方案
# -*- coding: utf-8 -*
try:
unicode
except:
unicode = str
_superscripts = u'⁻⁰¹²³⁴⁵⁶⁷⁸⁹'
_superscript_map = dict(zip(map(ord, u'-0123456789'), _superscripts))
def to_fancy(number, fmt='e'):
as_str = format(number, fmt)
as_str, _, exponent = as_str.partition('e')
if exponent: # will also print 10^0, add `and int(exponent)` to
# not add x10^0 at all.
exponent = unicode(int(exponent.replace('+', '')))
exponent = exponent.translate(_superscript_map)
as_str += u'×10' + exponent
return as_str
>>> print(to_fancy(0.00000000321))
3.210000×10⁻⁹
这是可行的,但并不代表指数。在我的问题中,我并没有完全诚实地尝试简化它,我已经更新了上面的内容。这是有效的,但并不代表指数。在我的问题中,我没有完全诚实地尝试简化它,我已经更新了上面的内容。在这个问题中,期望的输出是什么?像这样的Unicode字符:2×10⁸ 或者像2乘以10^{18}这样的TeX表示法?我认为两者都可以接受。但是我更喜欢TeX版本。@AnttiHaapala提供了一个别致的unicode版本,我在回答中添加了一个TeX化版本。谢谢你们两位。我已经接受了@Antihaapala的答案,但这两个答案都将被证明是有用的。在这个问题中,期望的结果到底是什么?像这样的Unicode字符:2×10⁸ 或者像2乘以10^{18}这样的TeX表示法?我认为两者都可以接受。但是我更喜欢TeX版本。@AnttiHaapala提供了一个别致的unicode版本,我在回答中添加了一个TeX化版本。谢谢你们两位。我接受了@antihaapala-answer,但两者都会被证明是有用的。@antihaapala-我对您的解决方案有一个稍微进一步的问题,当使用matplotlib-backend:MacOSX时,上标文本显示良好,但是当我将FIG保存为.png文件时,上标显示为空框。你知道为什么会这样吗?@Antihaapala-我对你的解决方案有一个稍微进一步的问题,当使用matplotlib后端:MacOSX时,上标文本看起来很好,但是当我将Fig保存为.png文件时,上标显示为空框。你有过这样的经历吗?