tags:

views:

73

answers:

2

Hi,

I have a large file with numbers in the form of 6,52353753563E-7. So there's an exponent in that string. float() dies on this.

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). I must say I'm surprised float() can't handle strings with such an exponent, this is pretty common stuff.

I'm using python 2.6, but 3.1 is an option if need be.

+4  A: 

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()

John Machin
Correct. Incidentally, if you type "6,52353753563E-7" into the Python prompt, it gets parsed as the tuple (6, 5235.3753563) -- fairly obvious why, it just looks odd.
benhoyt
Ah, thanks. I'll mark it as accepted when the timer lets me.
Lucas
On a related note, can I somehow make python recognize the comma? C# and Java can do this. Many places in the world use a comma as the decimal separator.
Lucas
Thanks for the `locale.atof()` edit.
Lucas
+1  A: 

Your problem is not in the exponent but in the comma. with python 3.1:

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