0

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

RaymondMachira
  • 344
  • 2
  • 5
  • 14
  • 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 Answers2

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.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

If you trust your input:

from __future__ import division

eval('14/15')
nullstellensatz
  • 756
  • 8
  • 18