Unsupported format?
I am trying to print a string with a float to 2 decimal places like this:
print "You have a discount of 20% and the final cost of the item is'%.2f' dollars." % price
But when I do this, I get this error:
ValueError: unsupported format character 'a' (0x61) at index 27
What does this mean and how can I prevent it?
source to share
The problem is yours 20%
, Python reads ...20% and...
as "% a" % price
and does not recognize %a
as format.
You can use 20%%
like @Anand, or you can use the line .format()
:
>>> price = 29.99
>>> print "You have a discount of 20% and the final cost of the item is {:.2f} dollars.".format(price)
You have a discount of 20% and the final cost of the item is 29.99 dollars.
Here :.2f
gives you 2 decimal places as for %.2f
.
source to share
An operator %
in strings treats its left-hand operand as a format specifier. All signs %
in it will be specially processed.
But %
after 20
it is not intended as such, and therefore must be properly escaped: write 20%%
. This speaks of the procedure for handling the format specifier to treat it as a literal %
.
Or, as Scott wrote, use new material .format()
.
source to share