float("1,000")出了什么问题?

0 投票
3 回答
812 浏览
提问于 2025-04-16 06:12

我对Python有点生疏了。我有一个包含成本的字符串列表。我想把它们转换成浮点数,但是当成本超过1000美元时,数值是用逗号来表示的。比如,float("1,000")会报错:

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

我知道这可能很简单,但你们有没有解决办法?

3 个回答

1

这个错误发生是因为你试图这样调用模块:

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

你应该这样做:

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

所以你可以这样简单地做:

2

在把数字转换成浮点数之前,先用re模块去掉任何的逗号格式。

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

decimal 不是 floatdecimal 是一个模块。这就是你遇到错误的原因。

至于逗号,先把它们去掉:

s = "1,000"
float(s.replace(",", "")) # = 1000.0

撰写回答