ValueError:基数为10的int()的无效文字:

时间:2016-06-06 16:32:24

标签: python

我有一本字典" item":

>>> item["value"]
Out[2]: u'$26,420'

我想将其转换为整数

26420

加载到db。到目前为止,我已经尝试过:

Out[2]: u'$26,420'
>>> item["value"][1:]
Out[3]: u'26,420'
>>> int(item["value"][1:])
Traceback (most recent call last):
  File "F:\envs\virtalenvs\teat\lib\site-packages\IPython\core\interactiveshell.py", line 2885, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-cd6c9e68ae50>", line 1, in <module>
    int(item["value"][1:])
ValueError: invalid literal for int() with base 10: '26,420'

这是最好的pythonic方式吗?

3 个答案:

答案 0 :(得分:3)

删除所有非数字字符:

>>> s = '$26,420'
>>> s = ''.join(c for c in s if c.isnumeric())
>>> int(s)
26420

答案 1 :(得分:2)

some_amount = "$12,345"
some_amount = int(some_amount.split("$")[1].replace(",", ""))
print some_amount #Will return 12345 as an int

答案 2 :(得分:1)

您可以将两个简单的替换链接在一起:

cur = int(cur.replace("$", "").replace(",", ""))