【发布时间】:2011-02-26 13:55:12
【问题描述】:
可能重复:
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(一百万)解析为整数值?
【问题讨论】:
可能重复:
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(一百万)解析为整数值?
【问题讨论】:
>>> a = '1,000,000'
>>> int(a.replace(',', ''))
1000000
>>>
【讨论】:
将 ',' 替换为 '',然后将整个内容转换为整数。
>>> int('1,000,000'.replace(',',''))
1000000
【讨论】:
还有一种简单的方法可以处理国际化问题:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
'en_US.UTF-8'
>>> 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.UTF-8') 即“UTF-8”,而不是“UTF8”。在我的 OSX 机器上,这似乎是正确的值。