How to convert rational and decimal number strings to floats in python?

ketorin picture ketorin · Feb 22, 2009 · Viewed 13.7k times · Source

How can I convert strings which can denote decimal or rational numbers to floats

>>> ["0.1234", "1/2"]
['0.1234', '1/2']

I'd want [0.1234, 0.5].

eval is what I was thinking but no luck:

>>> eval("1/2")
0

Answer

Ryan picture Ryan · Feb 22, 2009

I'd parse the string if conversion fails:

>>> def convert(s):
    try:
        return float(s)
    except ValueError:
        num, denom = s.split('/')
        return float(num) / float(denom)
...

>>> convert("0.1234")
0.1234

>>> convert("1/2")
0.5

Generally using eval is a bad idea, since it's a security risk. Especially if the string being evaluated came from outside the system.