new2Ubuntu
new2Ubuntu

Reputation: 53

Printing a formatted Float list in Python3

I am writing a program that does the following:

  1. Takes multiple inputs (floating point) delimited by commas
  2. Performs a calculation on all the elements of the list
  3. Outputs a list (floating point with two decimal places)

I have written the following program

import math

C = 50.0
H = 30.0
Q = []

D = input("Please input the D-Values\n").split(",")
[float(k) for k in D]
#[int(k) for k in D]

print("D = {}".format(D))

for i in D:
    j = (math.sqrt((2*C*float(i))/H))
    Q.append(j) 


print("The answers are")
print(Q)
print(type(Q[0]))
print("Q = {:.2f}".format(Q))

I am facing the following error when executing this program

Traceback (most recent call last):
  File "/home/abrar/pythonPrograms/Challange6.py", line 24, in <module>
    print("Q = {:.2f}".format(Q))
TypeError: non-empty format string passed to object.__format__

I tried to search for the solution to this problem but could not find an answer. The program works fine if {:.2f} is not included i.e. {} is used. However, the output is then very messy looking.

Any help is highly appreciated.

Upvotes: 5

Views: 9095

Answers (2)

hiro protagonist
hiro protagonist

Reputation: 46869

you are trying to format a list with the format string .2f - what you want is to format the floats inside your list. this is one way to fix that:

Q = [1.3, 2.4]
print(', '.join('{:.2f}'.format(f) for f in Q))
# 1.30, 2.40

starting from python 3.6 this could also be written as:

print(', '.join(f'{q:.2f}' for q in Q))

alternatively you could create you own class that accepts format strings:

class FloatList(list):

    def __init__(self, *args):
        super().__init__(args)

    def __format__(self, format_spec):
        return f'[{", ".join(f"{i:{format_spec}}" for i in self)}]'


fl = FloatList(0.1, 0.33, 0.632)
print(f"{fl:.2f}")  # [0.10, 0.33, 0.63]

Upvotes: 14

user2314737
user2314737

Reputation: 29327

You're trying to format a list but what you want is to format the elements of this list, hence you need to use *Q in place of Q (the * operator "unpacks" the list)

Here's a solution:

fmtL = "Q = " + ', '.join(["{:.2f}"]*len(Q))
print(fmtL.format(*Q))
Q = 1.83, 2.58, 3.16 

Upvotes: 2

Related Questions