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

I want to print something like this:

Hi 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 an error:

 KeyError: 's' 

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

+6
source share
1 answer

You use the numbered link in the second field; 0 indicates that you want to use the first parameter passed to str.format() (e.g. MyString ), and not the value MyFloat , which is parameter 1 .

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

Remove 0 :

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

since fields without a name or index number are automatically numbered or use the correct number:

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

If you chose the latter, it is better to be explicit sequentially and use 0 for the first placeholder:

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

Another option is to use named links:

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

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

+16
source

Source: https://habr.com/ru/post/974767/


All Articles