Home > OS >  Why Python format function is not working?
Why Python format function is not working?

Time:01-05

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?

CodePudding user response:

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))

CodePudding user response:

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]))
  •  Tags:  
  • Related