是否可以将字符串更改为使用没有 E 格式的数字浮动?
我在尝试时遇到错误float("0.333-5")
。Python 中的浮点数带有e
or E
。任何的想法?如何轻松添加E?
只需用 e 前面的减号替换减号
s = "0.333-5"
s = s.replace('-','e-')
float(s)
如果你可以有偶数加号,你将不得不做一个双重替换
s.replace('-','e-').replace('+','e+')
使用以下正则表达式:
import re
re.sub('(.)([-+]\d)', r'\1e\2', number_string)
哪里number_string = 0.333-5
。这将适用于负数,也适用于.5-5
.