Python parse comma-separated number into int [duplicate]

痞子三分冷 提交于 2019-11-26 09:49:18

问题


Possible Duplicate:
How do I use Python to convert a string to a number if it has commas in it as thousands separators?

How would I parse the string 1,000,000 (one million) into it\'s integer value in Python?


回答1:


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



回答2:


There's also a simple way to do this that should handle internationalization issues as well:

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

I found though that I have to explicitly set the locale first otherwise it doesn't work for me and I end up with an ugly traceback instead:

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'

So if that happens to you:

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



回答3:


Replace the ',' with '' and then cast the whole thing to an integer.

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


来源:https://stackoverflow.com/questions/2953746/python-parse-comma-separated-number-into-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!