Jibin
Jibin

Reputation: 3102

Error while converting to float

I am trying to read a file using csv.DictReader

I have a field that is supposed to be an integer.if it is empty i will set it as DEFAULT if it is an integer i do nothing.if it is not an integer i check if it is a quoted integer(like '1234').if so I will convert it to integer.Else an exception is raised.

it works as expected if its empty or it is an integer.Now if it is a quoted integer(like '1234') ,an exception is raised integer invalid literal for float(): '1234'.

it is not supposed to raise exception in this case.

I think it has something to do with the way DictReader reads the csv file. Everyhting else is just fine.Please help

 if not line[key]:
    line[key]='DEFAULT'
 elif not isinstance(line[key], (int, long, float)) :                        
    try:
      line[key]=float(line[key])
    except Exception,e :
      print e

Upvotes: 1

Views: 298

Answers (3)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29103

If your literal is something like "'1234'" or '"1234"' and '1234' you can use replace before converting:

data = ["'1234'", '"1234"', '1234', '', 1234]
[float(str(a).replace("'","").replace('"','')) if str(a).strip() else 'DEFAULT' for a in data]

Upvotes: 0

Niklas R
Niklas R

Reputation: 16870

This might not be the smartest way, but if you want to make sure there are only digits in your string, you could just remove all non-digits.

>>> import string
>>> extract = lambda s, charset: "".join(c for c in s if c in charset)
>>> float( extract("'h0424.234\"foo", string.digits + ".") )
424.234

Upvotes: 1

NPE
NPE

Reputation: 500357

The problem is that the single quotes are part of your string:

In [7]: float("'1234'")
ValueError: invalid literal for float(): '1234'

If you remove them, things should work:

In [8]: float("'1234'".strip("'"))
Out[9]: 1234.0

Upvotes: 4

Related Questions