I am using Python and fractions.Fraction()
I have a list of fractions that I want printed to look like this:
a = Fraction(0.25)
b = Fraction(1,3)
...
l = [a,b,...]
print(l)
>>>[1/4 , 1/3,...]
but instead I get:
a = Fraction(0.25)
b = Fraction(1,3)
...
l = [a,b,...]
print(l)
>>>[Fraction(1,4), Fraction(1,3),...]
I know I can get around this by iterating over the list I have and printing each element individually, but I wanted to know if there was an easier built in way before trying to do that.
Before you print you can invoke str
on each fraction to get the desired form:
>>> your_list = [Fraction(0.25), Fraction(1,3)]
>>> out_list = [str(frac) for frac in your_list]
>>> print(out_list)
['1/4', '1/3']
Try something like this:
from fractions import *
a = Fraction(0.25)
b = Fraction(1,3)
l = [a,b]
print(list(map(lambda x :x.__str__(),l)))
this invokes the str function of Fraction class, passing the objects a,b. or,
map(str,l)
also works as the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With