Kind of like this question, but in reverse.
Given a string like 1
, 1/2
, or 1 2/3
, what's the best way to convert it into a float? I'm thinking about using regexes on a case-by-case basis, but perhaps someone knows of a better way, or a pre-existing solution. I was hoping I could just use eval
, but I think the 3rd case prevents that.
maybe something like this (2.6+)
Depending on what syntax you want to support for your fractions,
eval('+'.join(s.split()))
(with true division in place -- i.e., Python 3 orfrom __future__ import division
in Python 2 -- might work. It would cover all the cases you mention, in particular.I tweaked James' answer a bit.
http://ideone.com/ItifKv
I see there are already several good answers here, but I've had good luck with this. It also has the benefit that it will tolerate non-fraction strings if you're parsing mixed sets of data, so there's no need to check if it's a fraction string or not upfront.
This implementation avoids using eval and works on pre-2.6 versions of Python.
To test: