简体   繁体   English

使用.format()打印变量字符串和舍入数字

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

I want to print something that looks like this: 我想打印看起来像这样的东西:

Hello ¦ 7.16 您好| 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: 或str而不是s我得到错误:

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? 或者我应该使用%s%s东西?

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 . 0表示您要使用传递给str.format()的第一个参数(例如MyString ),而不是MyFloat值,即参数1

Since you cannot use the .2f format on a string object, you get your error. 由于您无法在字符串对象上使用.2f格式,因此会出现错误。

Remove the 0 : 删除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: 如果你选择后者,最好是一致地显式并且为第一个占位符使用0

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. 注意str.format()的关键字参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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