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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With