简体   繁体   中英

Formatting in a code constantly causes the ValueError: Unknown format code 'f' for object of type 'str'?

Okay, so pretty much I've been getting the error that is described in the title. I know that it's a format problem with the code, but as far as solving it. All of the things regarding how to solve this have proven to be quite useless. Also, this code is for homework that I have if that provides any context on the matter. The contents of the code are based on a bill since the purpose of the program is for a tip calculator. I hope that provides context for that matter. Also, I am still relatively new with Python.

Anyways, to better show what the code is. Here's the code that is causing this:

print("\n\tBill Amount: ${0:.02f}%".format((meal))), "\n\tTip Suggested: ${0:0.2f}%".format((calculatedTip)), "\n\tTotal Bill ${0:.2f}%".format((total))

I've tried changing the "f" after the.02 to a "d" to see if that would help. I've tried adding parenthesis to see if that would influence the change, but all of these efforts were rather pointless, since the error was displayed regardless of the changes.

My main question is what can I do to fix this error? Anyways to whoever is reading this. I hope you have an amazing rest of your day cya!

Try this

print("\n\tBill Amount: ${0:.02f}%".format(float(meal)), "\n\tTip Suggested: ${0:0.2f}%".format(float(calculatedTip)), "\n\tTotal Bill ${0:.2f}%".format(float(total)))

This will work if all are numbers even if the numbers are in string format. Otherwise it will throw ValueError .

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