6

I am trying to print a line with a with a float formatter to 2 decimal points like this:

    print "You have a discount of 20% and the final cost of the item is'%.2f' dollars." % price

But when I do I get this error:

ValueError: unsupported format character 'a' (0x61) at index 27

What does this mean and how can I prevent it from happening?

UsuallyExplosive
  • 61
  • 1
  • 1
  • 3

3 Answers3

5

The issue is your 20%, Python is reading ...20% and... as "% a" % price and it doesn't recognize %a as a format.

You can use 20%% as @Anand points out, or you can use string .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 the :.2f gives you 2 decimal places as with %.2f.

Scott
  • 6,089
  • 4
  • 34
  • 51
3

I think the issue is with the single % sign after 20 , python maybe thinking it is a format specifier.

Try this -

print "You have a discount of 20%% and the final cost of the item is'%.2f' dollars." % price
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
0

The % operator on strings treats its left operand as a format specifier. All % signs in it will be treated specially.

But the % after the 20 is not intended as such and thus must be escaped properly: write 20%%. This tells the format specifier processing routine to treat it as a literal %.

Or, as Scott wrote, use the newer .format() stuff.

glglgl
  • 89,107
  • 13
  • 149
  • 217