Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a string representing a float *with an exponent* in Python

Tags:

python

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.

like image 602
Lucas Avatar asked May 12 '10 22:05

Lucas


People also ask

How do you convert a string to a float in Python?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

What does %% in Python do?

The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It's used to get the remainder of a division problem.


2 Answers

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

like image 78
John Machin Avatar answered Sep 20 '22 09:09

John Machin


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

>>> a = "6.52353753563E-7"
>>> float(a)
6.52353753563e-07
like image 41
joaquin Avatar answered Sep 19 '22 09:09

joaquin