davidj411 at gmail
May 28, 2008, 10:41 AM
Post #11 of 13
On May 28, 2:22 am, Kam-Hung Soh <kamhung....@gmail.com> wrote:
Re: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"'
[In reply to]
> 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):
> return int(datum)
> return float(datum)
> 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', '',
> 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.