Spike Williams
Spike Williams

Reputation: 37315

How to convert a numeric string with place-value commas into an integer?

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?

Upvotes: 7

Views: 4867

Answers (4)

ibz
ibz

Reputation: 46709

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.

Upvotes: 9

ghostdog74
ghostdog74

Reputation: 342353

>>> s="1,374"
>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, '')
'en_US.UTF-8'
>>> locale.atoi(s)
1374

Upvotes: 3

Yin Zhu
Yin Zhu

Reputation: 17119

int("1,374".replace(",",""))

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

locale.atoi(), after setting an appropriate locale.

Upvotes: 4

Related Questions