Python将逗号分隔的数字解析为int

时间:2010-06-01 22:11:47

标签: python string-conversion

  

可能重复:
  How do I use Python to convert a string to a number if it has commas in it as thousands separators?

如何在Python中将字符串1,000,000(一百万)解析为整数值?

3 个答案:

答案 0 :(得分:85)

>>> a = '1,000,000'
>>> int(a.replace(',', ''))
1000000
>>> 

答案 1 :(得分:33)

还有一种简单的方法可以解决国际化问题:

>>> import locale
>>> locale.atoi("1,000,000")
1000000
>>> 

我发现虽然我必须首先明确设置语言环境,否则它对我不起作用而我最终会得到一个丑陋的追溯:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/locale.py", line 296, in atoi
    return atof(str, int)
  File "/usr/lib/python2.6/locale.py", line 292, in atof
    return func(string)
ValueError: invalid literal for int() with base 10: '1,000,000'

所以如果你遇到这种情况:

>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF8')
'en_US.UTF8'
>>> locale.atoi("1,000,000")
1000000
>>> 

答案 2 :(得分:9)

将','替换为'',然后将整个事物转换为整数。

>>> int('1,000,000'.replace(',',''))
1000000