Python Fraction - How to convert a string or float to a fraction

A fraction is declared using the Fraction class in Python.

from fractions import Fraction

a = Fraction(2, 5)

print(a)  # 2/5
print(type(a))  # <class 'fractions.Fraction'>

If a Fraction instance has two arguments, the first one is numerator and the second one is denominator.

Fraction(numerator, denominator)

Convert a number to a fraction

If an instance has only one argument, it is automatically converted to the fraction.

from fractions import Fraction

a = Fraction('0.2')
b = Fraction('.2')
c = Fraction(0.2)
d = Fraction(.2)

print(a)  # 1/5
print(b)  # 1/5
print(c)  # 3602879701896397/18014398509481984
print(d)  # 3602879701896397/18014398509481984

Note that a string is converted properly but a float is converted to the strange value.

The string of a minus value is also properly converted to the fraction. Surprisingly, even if the argument has meaningless spaces, the Fraction ignores them.

from fractions import Fraction

a = Fraction('-0.2')
b = Fraction('-.2')
c = Fraction('   0.2      ')

print(a)  # -1/5
print(b)  # -1/5
print(c)  # 1/5

Python Fraction

Python Tutorial