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

Kam-Hung Soh kamhung.soh at gmail.com
Wed May 28 02:22:00 EDT 2008


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>




More information about the Python-list mailing list