In Python, what is a clean and elegant way to convert strings like "1,374" or "21,000,000" to int values like 1374 or 21000000?
Asked
Active
Viewed 4,495 times
4 Answers
9
It really depends where you get your number from.
If the number you are trying to convert comes from user input, use locale.atoi()
. That way, the number will be parsed in a way that is consistent with the user's settings and thus expectations.
If on the other hand you read it, let's say, from a file, that always uses the same format, use int("1,234".replace(",", ""))
or int("1.234".replace(".", ""))
depending on your situation. This is not only easier to read and debug, but it's not affected by the user's locale setting, so your parser will work on any system.

ibz
- 44,461
- 24
- 70
- 86
4
locale.atoi()
, after setting an appropriate locale.

Ignacio Vazquez-Abrams
- 776,304
- 153
- 1,341
- 1,358
-
+1 This is better than just replacing commas with empty-strings, because in some locales commas are used as decimal separators, while periods play the part of delimiting the thousands, millions etc. – Tarydon Feb 22 '10 at 02:28
-
Depends what you're trying to parse. User input? Or a file with a fixed format (say a CSV you get from a legacy system)? Not the same. See my answer below. – ibz Feb 22 '10 at 02:55
3
>>> s="1,374"
>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, '')
'en_US.UTF-8'
>>> locale.atoi(s)
1374

ghostdog74
- 327,991
- 56
- 259
- 343