views:

32780

answers:

9

This should be simple - In python, how can I parse a numeric string like "545.2222" to its corresponding float value, 542.2222 or "31" to an integer, 31?

EDIT: I just wanted to know how to parse a float string to a float, and (separately) an int string to an int. Sorry for the confusing phrasing/original examples on my part.

At any rate, the answer from Harley is what I needed.

+4  A: 

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

codelogic
This will give you a float object if your string happens to be "0" or "0.0", rather than the int it gives for other valid numbers.
Brian
+29  A: 
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
Harley
What about rounding? 545.7 should be 546. float(a+0.5). See below.
Nick
A: 

May be you are looking out for something like this.

In [78]: s="545.22222"

In [79]: eval(s)
Out[79]: 545.22221999999999

In [80]: import math

In [81]: math.ceil(eval(s))
Out[81]: 546.0

In [82]: math.floor(eval(s))
Out[82]: 545.0

floor and ceil are more relevant in some cases then just int().

Cheers

JV
I believe is generally bad practice to use eval in this way. float() and int() should be used. (Assuming input is read from another source)>>> open('dummy.txt','w').close()>>> os.path.exists('dummy.txt')True>>> eval('os.remove("dummy.txt")')>>> os.path.exists('dummy.txt')False
monkut
second time i saw ipy today, and never heard of it before. slick interpreter.
Dustin Getz
@monkut: I cannot make out what u mean't by the example: (Assuming input is read from another source) >>> open('dummy.txt','w').close() >>> os.path.exists('dummy.txt') True >>> eval('os.remove("dummy.txt")') >>> os.path.exists('dummy.txt') False )can u elaborate in words what u meant
JV
@JV: monkut is referring to the fact that if your input comes from some untrusted source, it could be doing anything when evaled. Not just producing an integer, but deleting files (as in monkuts' example), downloading viruses - pretty much anything. Hence the danger flags for eval in such cases.
Brian
+2  A: 

codelogic and harley are correct, but keep in mind if you know the string is an integer (e.g. 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]
>>>

Only good if they're all the same type.

Chris Cameron
+1  A: 

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 )

Works like this...

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


Edit. 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.

S.Lott
You've got to careful of your input values with this one. eval will execute any functions passed to it.
recursive
This is dangerous as it allows easy code injection when the input comes from outside and is not carefully checked.
Ber
import os is a statement that wouldn't work, however __import__("os").abort() would be possible
DasIch
+4  A: 
def num (s):
    try:
        return int(s)
    except exceptions.ValueError:
        return float(s)
Javier
This is exactly what I've used in the past.
Boojum
+17  A: 
float(x) if '.' in x else int(x)
Dino Viehland
Not really what I was asking, but thats a damn cool solution to the common misconception.
Tristan Havelick
I know you use this form a lot, but if you could note as (2.5+), it might prevent some insanity when 2.4 folk try to use it :)
Gregg Lind
+1  A: 
try:
    float(x) if '.' in x else int(x)
except ValueError:
    print "Not a numeric string."
mluebke
A: 

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)
Nick