# Parse String to Float or Int

0 votes
asked Dec 19, 2008

In Python, how can I parse a numeric string like `"545.2222"` to its corresponding float value, `542.2222`? Or parse the string `"31"` to an integer, `31`?

I just want to know how to parse a float string to a float, and (separately) an int string to an int.

## 20 Answers

0 votes
answered Dec 19, 2008

`float("545.2222")` and `int(float("545.2222"))`

0 votes
answered Dec 19, 2008
``````>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
``````
0 votes
answered Dec 19, 2008

Users codelogic and harley are correct, but keep in mind if you know the string is an integer (for example, 545) you can call int("545") without first casting to float.

If your strings are in a list, you could use the map function as well.

``````>>> x = ["545.0", "545.6", "999.2"]
>>> map(float, x)
[545.0, 545.60000000000002, 999.20000000000005]
>>>
``````

It is only good if they're all the same type.

0 votes
answered Dec 19, 2008 by

Here's another interpretation of your question (hint: it's vague). It's possible you're looking for something like this:

``````def parseIntOrFloat( aString ):
return eval( aString )
``````

It works like this...

``````>>> parseIntOrFloat("545.2222")
545.22220000000004
>>> parseIntOrFloat("545")
545
``````

Theoretically, there's an injection vulnerability. The string could, for example be `"import os; os.abort()"`. Without any background on where the string comes from, however, the possibility is theoretical speculation. Since the question is vague, it's not at all clear if this vulnerability actually exists or not.

0 votes
answered Dec 19, 2008 by
``````def num(s):
try:
return int(s)
except ValueError:
return float(s)
``````
0 votes
answered Dec 19, 2008
``````float(x) if '.' in x else int(x)
``````
0 votes
answered Oct 21, 2010 by

You need to take into account rounding to do this properly.

I.e. int(5.1) => 5 int(5.6) => 5 -- wrong, should be 6 so we do int(5.6 + 0.5) => 6

``````def convert(n):
try:
return int(n)
except ValueError:
return float(n + 0.5)
``````
0 votes
answered Sep 28, 2011 by

The question seems a little bit old. But let me suggest a function, parseStr, which makes something similar, that is, returns integer or float and if a given ASCII string cannot be converted to none of them it returns it untouched. The code of course might be adjusted to do only what you want:

``````   >>> import string
>>> parseStr = lambda x: x.isalpha() and x or x.isdigit() and \
...                      int(x) or x.isalnum() and x or \
...                      len(set(string.punctuation).intersection(x)) == 1 and \
...                      x.count('.') == 1 and float(x) or x
>>> parseStr('123')
123
>>> parseStr('123.3')
123.3
>>> parseStr('3HC1')
'3HC1'
>>> parseStr('12.e5')
1200000.0
>>> parseStr('12\$5')
'12\$5'
>>> parseStr('12.2.2')
'12.2.2'
``````
0 votes
answered Mar 1, 2012 by

This is another method which deserves to be mentioned here, 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
``````
0 votes
answered Apr 16, 2013 by

The YAML parser can help you figure out what datatype your string is. Use `yaml.load()`, and then you can use `type(result)` to test for type:

``````>>> import yaml

>>> a = "545.2222"
>>> result = yaml.load(a)
>>> result
545.22220000000004
>>> type(result)
<type 'float'>

>>> b = "31"
>>> result = yaml.load(b)
>>> result
31
>>> type(result)
<type 'int'>

>>> c = "HI"
>>> result = yaml.load(c)
>>> result
'HI'
>>> type(result)
<type 'str'>
``````