简体   繁体   中英

Unsupported format character?

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?

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 .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM