Why Python format function is not working?

Question:

In python I wrote:

list_of_assets = []
list_of_assets.append(('A', 'B', 'C'))
for asset in list_of_assets:
    print('{:15}   {:30}   {:30}'.format([asset[0], asset[1], asset[2]]))

But I get:

print('{:15}   {:30}   {:30}'.format([asset[0], asset[1], asset[2]]))
TypeError: non-empty format string passed to object.__format__

why is that?

Asked By: Algo

||

Answers:

Don’t wrap the format parameters in a list:

list_of_assets = []
list_of_assets.append(('A', 'B', 'C'))
for asset in list_of_assets:
    #                              here  ↓                  and here ↓
    print('{:15}   {:30}   {:30}'.format(asset[0], asset[1], asset[2]))

output:

A                 B                                C                             

Even better, you could use parameter expansion:

for asset in list_of_assets:
    print('{:15}   {:30}   {:30}'.format(*asset))
Answered By: mozway

The error came because you passed a list argument to the format function. Pass individual elements of the list instead.

Your code should be like this:

list_of_assets = []
list_of_assets.append(('A', 'B', 'C'))
for asset in list_of_assets:
    print('{:15}   {:30}   {:30}'.format(asset[0], asset[1], asset[2]))
Answered By: Ajeigbe Oladayo

Use this code

list_of_assets = []
list_of_assets.append(('A', 'B', 'C'))
for asset in list_of_assets:
    print('{:15}   {:30}   {:30}'.format(asset[0],asset[1],asset[2]))
Answered By: Venkydeexu18
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.