Python parse comma-separated number into int

PythonString Conversion

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.atoi("1,000,000")
1000000
>>> 

I found that I have to explicitly set the locale first as above, 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'

Solution 3 - Python

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionroryfView Question on Stackoverflow
Solution 1 - PythonjoaquinView Answer on Stackoverflow
Solution 2 - PythonKhorkrakView Answer on Stackoverflow
Solution 3 - PythonjathanismView Answer on Stackoverflow