簡體   English   中英

使用.format()打印變量字符串和舍入數字

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

我想打印看起來像這樣的東西:

您好| 7.16

這是我正在使用的代碼

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

但我得到錯誤:

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

如果我嘗試:

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

或str而不是s我得到錯誤:

KeyError: 's'

我有什么想法可以用圓形浮點數打印變量字符串? 或者我應該使用%s%s東西?

您在第二個字段中使用了編號引用 ; 0表示您要使用傳遞給str.format()的第一個參數(例如MyString ),而不是MyFloat值,即參數1

由於您無法在字符串對象上使用.2f格式,因此會出現錯誤。

刪除0

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

由於沒有名稱或索引號的字段是自動編號的,或使用正確的數字:

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

如果你選擇后者,最好是一致地顯式並且為第一個占位符使用0

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

另一種選擇是使用命名引用:

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

注意str.format()的關鍵字參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM