Python的解析逗号分隔的数字转换成int
问题描述:
可能重复:
How do I use Python to convert a string to a number if it has commas in it as thousands separators?Python的解析逗号分隔的数字转换成int
我将如何解析字符串1,000,000
(一百万)到它在Python整数值?
答
>>> a = '1,000,000'
>>> int(a.replace(',', ''))
1000000
>>>
答
将','替换为'',然后将整个东西都转换为整数。
>>> int('1,000,000'.replace(',',''))
1000000
答
还有一个简单的方法来做到这一点,应处理国际问题,以及:
>>> 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
>>>
+0
您的意思是: 'locale.setlocale(locale.LC_ALL,'en_US.UTF-8')' Ie “UTF-8”,而不是“UTF8”。在我的OSX机器上,似乎是正确的值。 – 2018-01-14 23:35:21
请参阅http://stackoverflow.com/questions/1779288/how-do-i-use-python-to-convert-a-string-to-a-number-if-it-has-commas-in -it-as-tho/1779324 – unutbu 2010-06-01 22:15:29