开发者

What's wrong with float("1,000")?

开发者 https://www.devze.com 2023-01-22 02:58 出处:网络
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

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 recen开发者_运维知识库t 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?


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


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

>>> import re
>>> re.sub(",", "", "1000,00,00")
'10000000'
>>> 


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

0

精彩评论

暂无评论...
验证码 换一张
取 消