The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

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

--

Chapters
00:00 How Do I Parse A String To A Float Or Int?
00:36 Accepted Answer Score 3083
00:43 Answer 2 Score 580
00:50 Answer 3 Score 167
01:13 Answer 4 Score 89
02:31 Thank you

--

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

--

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.