heej heej - 1 month ago 21
Python Question

Invalid format specifier for thousands place

I am trying to make a simple chart like output. Here are strings that I want to display:

a = "name", b = "10000.00", c = "code", d = "45.60", e = "30.00"

print("{0:20}${1:,20}{2:20}${3:,20}${4:,<5}".format(a,b,c,d,e),file=outfile)


I put "," to indicate thousands place in each format specifier in which I want them to be output as currency. It reports the error:

print("{0:20}${1:,20}{2:20}${3:20}${4:<5}".format(a,b,c,d,e),file=outfile)
ValueError: Invalid format specifier


What did I do wrong?

Answer

As per the docs, width has to go after comma. Moreover, your b variable has to be a number (and not a string, as in your MWE):

>>> x = 10000.0
>>> '{0:20,}'.format(x)
'            10,000.0'
Comments