convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'

davidj411 davidj411 at gmail.com
Wed May 28 13:41:51 EDT 2008


On May 28, 2:22 am, Kam-Hung Soh <kamhung.... at gmail.com> wrote:
> David Jackson wrote:
> > i used the csv module and saved its contents to a list.
>
> > ['Date', 'No.', 'Description', 'Debit', 'Credit']
> > ['3/17/2006', '5678', 'ELECTRONIC PAYMENT', '', '11.45']
> > ['3/04/2007', '5678', 'THE HOME DEPOT 263 SomeCity FL', '', '25.40']
>
> > the credit/debit fields are strings.
> > what should i have done within the CSV module to make numbers appear as
> > numbers?
> > how can i remove the quotes to make them numbers? i realize i posted a
> > solution to this once before (same posting thread) but i am thinking
> > there is a better method.
>
> There doesn't seem to be a way to describe how specific columns should
> be processed in the csv module.  You could define a conversion function
> that "guesses" the best conversion, for example:
>
> def str2num(datum):
>         try:
>                 return int(datum)
>         except:
>                 try:
>                         return float(datum)
>                 except:
>                         return datum
>
> for row in csv.reader(file(r'Transaction.csv')):
>         [str2num(cell) for cell in row]
>
> ['Date', 'No.', 'Description', 'Debit', 'Credit']
> ['3/17/2006', 5678, 'ELECTRONIC PAYMENT', '', 11.449999999999999]
> ['3/04/2007', 5678, 'THE HOME DEPOT 263 SomeCity FL', '',
> 25.399999999999999]
>
> --
> Kam-Hung Soh <a href="http://kamhungsoh.com/blog">Software Salariman</a>

I like the str2num function approach, but then i get left with a float
that has more than 2 decimal spaces , i.e. 11.50 becomes
11.449999999999999 and round will not fix that.



More information about the Python-list mailing list