How would I parse the string 1,000,000
(one million) into it's integer value in Python?
Asked
Active
Viewed 1.3e+01k times
92

Henry Ecker
- 34,399
- 18
- 41
- 57

roryf
- 29,592
- 16
- 81
- 103
-
3See 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 Jun 01 '10 at 22:15
3 Answers
60
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'
-
4Do you mean: `locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')` I.e. "UTF-8", not "UTF8". On my OSX machine that seems to be the correct value. – Alasdair Mackintosh Jan 14 '18 at 23:35
-
1This should be the accepted answer. The comma-replacement hack is brittle and i18n-breaking. – Reinderien Sep 13 '18 at 02:52
-
1
-
@Seperman Under the hood, `locale.atoi` and friends just do `val.replace(sep, '')`, where `sep` is the thousands separator defined in the locale convention. – snakecharmerb Feb 16 '22 at 08:29
-
13
Replace the ',' with '' and then cast the whole thing to an integer.
>>> int('1,000,000'.replace(',',''))
1000000

jathanism
- 33,067
- 9
- 68
- 86