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

Viewed 86

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.

4 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']

Defining fractionslist as [Fraction(3, 4)] * 10, I don't think it can get any shorter and more readable than this:

>>> print(*fractionslist)
3/4 3/4 3/4 3/4 3/4 3/4 3/4 3/4 3/4 3/4

The asterisk unpacks the values in fractionslist, and print automatically converts the values to string.

A variant on this, but separated by commas:

>>> print(*fractionslist, sep = ", ")
3/4, 3/4, 3/4, 3/4, 3/4, 3/4, 3/4, 3/4, 3/4, 3/4

You can also map all the items in the list to str, then join them:

>>> print(", ".join(map(str, fractionslist)))
3/4, 3/4, 3/4, 3/4, 3/4, 3/4, 3/4, 3/4, 3/4, 3/4

Or you can print them individually like you pointed out but without newlines (note that it does put a space at the end):

>>> for fraction in fractionslist: print(fraction, end=" ")
3/4 3/4 3/4 3/4 3/4 3/4 3/4 3/4 3/4 3/4 

Given a=Fraction(3,7), str(a) should return '3/7'

Then printing a list of fractions is probably easiest and most attractive by unpacking a map:

LF = [Fraction(a*2+1, a*2+5) for a in range(1,21)]
print(*map(str,LF), sep=", ")

gives

3/7, 5/9, 7/11, 9/13, 11/15, 13/17, 15/19, 17/21, 19/23, 21/25, 23/27, 25/29, 27/31, 
29/33, 31/35, 33/37, 35/39, 37/41, 39/43, 41/45

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.

Related