convert mixed number string to float 1

convert mixed number string to float

from fractions import Fraction
float(sum(Fraction(s) for s in '1 2/3'.split()))

Here is what the above code is Doing:
1. The sum() function takes an iterable and returns the sum of its elements.
2. The generator expression (s for s in ‘1 2/3’.split()) returns a generator that yields the strings ‘1’, ‘2/3’, and ” (the empty string at the end is due to the trailing space).
3. The float() function takes a string and returns a floating-point number.
4. The Fraction() function takes a string like ‘2/3’ and returns a Fraction instance.
5. The generator expression (Fraction(s) for s in ‘1 2/3’.split()) returns a generator that yields the Fraction instances Fraction(1, 1), Fraction(2, 3), and Fraction(0, 1).
6. The sum() function takes the generator expression (Fraction(s) for s in ‘1 2/3’.split()) and returns the sum of its elements, which is the Fraction instance Fraction(7, 3).
7. The float() function takes the Fraction instance Fraction(7, 3) and returns the floating-point number 2.3333333333333335.

Similar Posts