tags:

views:

113

answers:

4

Very rusty with my Python. I have a list of Cost as strings. I'm trying to convert them to floats but when the cost is above $1000, the value is represented with a comma. float("1,000") returns an error:

Traceback (most recent call last):
 File "<pyshell#5>", line 1, in <module>
   decimal("1,000")
TypeError: 'module' object is not callable

I know it's probably trivial but do you have a solution?

+1  A: 

Don't use commas in the floats :)

Lucho
trust me I don't want to but that's how I get the data from the CSV...
datayoda
so, just remove the comma - `str.replace(old, new)`
Lucho
+3  A: 

decimal is not float. decimal is a module. That is the reason for the error you get.

As for the commas, drop them first:

s = "1,000"
float(s.replace(",", "")) # = 1000.0
Muhammad Alkarouri
+2  A: 

Use re to remove any "," formatting before you convert to float.

>>> import re
>>> re.sub(",", "", "1000,00,00")
'10000000'
>>> 
pyfunc
`re` is overkill. `replace` is sufficient as shown in my answer.
Muhammad Alkarouri
thank you, but agree that doing import for this is overkill
datayoda
+1  A: 

The error that raise is because you are trying to call the module like this:

>>> import decimal
>>> decimal("")
TypeError: 'module' object is not callable

you should rather do:

>>> import locale
>>> import decimal
>>> locale.setlocale(locale.LC_ALL, '')
>>> decimal.Decimal(locale.atoi("1,000"))
Decimal('1000')

so you can just do it like this

singularity
In the question the comma is used as a thousand separator. Your result is different.
Muhammad Alkarouri
@Muhammad Alkarouri: ohhh thanks i didn't read the question very well :)
singularity