Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 500
ketorin Avatar asked Feb 22 '09 22:02

ketorin


1 Answers

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.

like image 54
Ryan Avatar answered Sep 18 '22 17:09

Ryan