简体   繁体   English

在Python中解析表示带*浮点数的字符串

[英]Parsing a string representing a float *with an exponent* in Python

I have a large file with numbers in the form of 6,52353753563E-7 . 我有一个很大的文件,数字形式为6,52353753563E-7 So there's an exponent in that string. 因此,该字符串中有一个指数。 float() dies on this. float()在此死亡。

While I could write custom code to pre-process the string into something float() can eat, I'm looking for the pythonic way of converting these into a float (something like a format string passed somewhere). 虽然我可以编写自定义代码来将字符串预处理为float()可以食用的东西,但我正在寻找将这些字符串转换为float的pythonic方式(类似于在某处传递的格式字符串)。 I must say I'm surprised float() can't handle strings with such an exponent, this is pretty common stuff. 我必须说让我感到惊讶的是float()不能处理如此指数的字符串,这是很常见的东西。

I'm using python 2.6, but 3.1 is an option if need be. 我正在使用python 2.6,但如果需要的话,可以选择3.1。

Nothing to do with exponent. 与指数无关。 Problem is comma instead of decimal point. 问题是逗号而不是小数点。

>>> float("6,52353753563E-7")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 6,52353753563E-7
>>> float("6.52353753563E-7")
6.5235375356299998e-07

For a general approach, see locale.atof() 有关一般方法,请参见locale.atof()

Your problem is not in the exponent but in the comma. 您的问题不在指数中,而是在逗号中。 with python 3.1: 使用python 3.1:

>>> a = "6.52353753563E-7"
>>> float(a)
6.52353753563e-07

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 python 中将 E 表示法字符串转换为具有固定指数的浮点数 - How to convert a E notation string to a float with fixed exponent in python 如何使用Python字符串格式将表示美分的整数转换为表示美元的浮点数? - How to use Python string formatting to convert an integer representing cents to a float representing dollars? 解析字符串以浮动python时出现意外的EOF - unexpected EOF while parsing string to float python 是否有可能强制浮点数的指数或有效数与另一个浮点数(Python)相匹配? - Is it possible to force exponent or significand of a float to match another float (Python)? 在Python中使用带浮点值的指数运算符(**)时出现意外输出 - Unexpected output when using exponent operator(**) with float value in Python 如何在python中处理64float精度的指数溢出? - How to deal with exponent overflow of 64float precision in python? Python:以字符串形式显示的指数字符 - Python: Exponent-Characters shown in string 有没有办法使用 python 在字符串中写入指数? 不只是^2 - Is there a way to write an exponent in a string using python? Not just ^2 在Python中从Float解析日期 - Parsing Dates from Float in Python 代表参数的Python动态字符串[i] - Python dynamic string representing argument[i]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM