spizwhiz
spizwhiz

Reputation: 127

Invalid literal for float

I am having the hardest time figuring out why the scientific notation string I am passing into the float() function will not work:

time = []
WatBalR = []
Area = np.empty([1,len(time)])
Volume = np.empty([1,len(time)])
searchfile = open("C:\GradSchool\Research\Caselton\Hydrus2d3d\H3D2_profile1v3\Balance.out", "r")
for line in searchfile:
    if "Time" in line: 
        time.append(re.sub("[^0-9.]", "", line))
    elif "WatBalR" in line: 
        WatBalR.append(re.sub("[^0-9.]", "", line))
    elif "Area" in line:
        Area0 = re.sub("[^0-9.\+]", "", line)
        print repr(Area0[:-10])
        Area0 = float(Area0[:-10].replace("'", ""))
        Area = numpy.append(Area, Area0)
    elif "Volume" in line:
        Volume0 = re.sub("[^0-9.\+]", "", line)
        Volume0 = float(Volume0[:-10].replace("'", ""))
        Volume = numpy.append(Volume, Volume0)
searchfile.close()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-80-341de12bbc94> in <module>()
     13         Area0 = re.sub("[^0-9.\+]", "", line)
     14         print repr(Area0[:-10])
---> 15         Area0 = float(Area0[:-10].replace("'", ""))
     16         Area = numpy.append(Area, Area0)
     17     elif "Volume" in line:
    ValueError: invalid literal for float(): 0.55077+03

However, the following works:

float(0.55077+03)
3.55077

If I put quotes around the argument, the same invalid literal comes up, but I am tried to remove the quotes from the string and cannot seem to do so.

Upvotes: 0

Views: 718

Answers (2)

mgilson
mgilson

Reputation: 309969

float(0.55077+03) adds 3 to .55077 and then converts it to a float (which it already is).

Note that this also only works on python2.x. On python3.x, 03 is an invalid token -- the correct way to write it there is 0o3...

float('0.55077+03') doesn't work (and raises the error that you're seeing) because that isn't a valid notation for a python float. You need: float('0.55077e03') if you're going for a sort of scientific notation. If you actually want to evaluate the expression, then things become a little bit trickier . . .

Upvotes: 1

user2357112
user2357112

Reputation: 281252

0.55077+03 is 0.55077 added to 03. You need an e for scientific notation:

0.55077e+03

Upvotes: 1

Related Questions