The Python Oracle

How do I parse a string to a float or int?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Romantic Lands Beckon

--

Chapters
00:00 Question
00:46 Accepted answer (Score 3025)
00:56 Answer 2 (Score 590)
03:10 Answer 3 (Score 574)
03:21 Answer 4 (Score 163)
03:52 Thank you

--

Full question
https://stackoverflow.com/questions/3799...

Question links:
[Convert integer to string in Python]: https://stackoverflow.com/questions/9616...
[Converting a float to a string without rounding it]: https://stackoverflow.com/questions/1317...
[How can I read inputs as numbers?]: https://stackoverflow.com/questions/2044...

Answer 1 links:
[Checking if a string can be converted to float in Python]: https://stackoverflow.com/questions/7360...
[Python]: http://en.wikipedia.org/wiki/Python_%28p...

Answer 3 links:
[ast.literal_eval]: http://docs.python.org/library/ast.html#...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #parsing #floatingpoint #typeconversion #integer

#avk47



ACCEPTED ANSWER

Score 3083


>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545



ANSWER 2

Score 580


def num(s):
    try:
        return int(s)
    except ValueError:
        return float(s)



ANSWER 3

Score 167


Another method which deserves to be mentioned here is ast.literal_eval:

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

That is, a safe 'eval'

>>> import ast
>>> ast.literal_eval("545.2222")
545.2222
>>> ast.literal_eval("31")
31



ANSWER 4

Score 89


Localization and commas

You should consider the possibility of commas in the string representation of a number, for cases like float("545,545.2222") which throws an exception. Instead, use methods in locale to convert the strings to numbers and interpret commas correctly. The locale.atof method converts to a float in one step once the locale has been set for the desired number convention.

Example 1 -- United States number conventions

In the United States and the UK, commas can be used as a thousands separator. In this example with American locale, the comma is handled properly as a separator:

>>> import locale
>>> a = u'545,545.2222'
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.atof(a)
545545.2222
>>> int(locale.atof(a))
545545
>>>

Example 2 -- European number conventions

In the majority of countries of the world, commas are used for decimal marks instead of periods. In this example with French locale, the comma is correctly handled as a decimal mark:

>>> import locale
>>> b = u'545,2222'
>>> locale.setlocale(locale.LC_ALL, 'fr_FR')
'fr_FR'
>>> locale.atof(b)
545.2222

The method locale.atoi is also available, but the argument should be an integer.