简体   繁体   中英

Using .format() to print a variable string and a rounded number

I want to print something that looks like this:

Hello ¦ 7.16

This is the code I'm using

MyString = 'Hello'
MyFloat = 7.157777777
print "{}  ¦  {0:.2f}".format(MyString, MyFloat)

But I get the error:

ValueError: cannot switch from automatic field numbering to manual field specification

If I try:

MyString = 'Hello'
MyFloat = 7.157777777
print "{s}  ¦  {0:.2f}".format(MyString, MyFloat)

or str instead of s I get the error:

KeyError: 's'

Any ideas how I can print a variable string with a rounded float? Or is there something like %s that I should be using?

You are using a numbered reference in the second field; the 0 indicates you want to use the first parameter passed to str.format() (eg MyString ), not the MyFloat value which is parameter 1 .

Since you cannot use the .2f format on a string object, you get your error.

Remove the 0 :

print "{}  ¦  {:.2f}".format(MyString, MyFloat)

as fields without a name or index number are auto-numbered, or use the correct number:

print "{}  ¦  {1:.2f}".format(MyString, MyFloat)

If you chose the latter, it's better to be explicit consistently and use 0 for the first placeholder:

print "{0}  ¦  {1:.2f}".format(MyString, MyFloat)

The other option is to use named references:

print "{s}  ¦  {f:.2f}".format(s=MyString, f=MyFloat)

Note the keyword arguments to str.format() there.

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