How to change a '14/15' string to a float? I am trying to extract data from a text file would like to convert '1/3' to a float. float('1/3') doesn't work. I was thinking about splitting into two parts at '/' by 1 and 3 then dividing, but it seems cludgy. Is there a more pythonic way to do this? I'm using Python 2.7
Asked
Active
Viewed 83 times
0
-
Do you only need to parse `X/Y`, or are you looking for a more general expression evaluator? – NPE Oct 07 '14 at 21:06
2 Answers
2
If you only ever need to evaluate simple X/Y
fractions:
s = "14/15"
num, denom = map(float, s.split("/", 1))
print(num / denom)
If you need a more complete expression evaluator, take a look at the asteval
module.
Using eval()
might also see like a nice easy way to do it, but I'd advise against it for security reasons.
0
If you trust your input:
from __future__ import division
eval('14/15')

nullstellensatz
- 756
- 8
- 18
-
-
Also, really dangerous if you don't know where your data came from. – Ned Batchelder Oct 08 '14 at 14:34