Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Fraction" type appears along with fractions in my printed List

Tags:

python

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.

like image 363
Phostration Avatar asked Sep 06 '25 03:09

Phostration


2 Answers

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']
like image 134
Mustafa Aydın Avatar answered Sep 07 '25 20:09

Mustafa Aydın


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.

like image 36
sathvik a Avatar answered Sep 07 '25 19:09

sathvik a