你好,我目前正在學習如何在python 2.7中使用字符串格式,並且im在特定場景中產生的特定錯誤消息中稍有混淆。python 2.7中的字符串格式
確定這樣的第一塊代碼,我已經寫運行按預期它是:
print "My name is %s and my age is %d years old!" % ('Bob', 30)
的稍微改變代碼的第二片也運行良好,它是(使用兩個(或多個)轉換):
print "My name is %s and my age is %s years old!" % ('Bob', 30)
然而第三代碼段輸出和錯誤(使用一個(d)和一個(或多個)轉換):
print "My name is %d and my age is %s years old!" % ('Bob', 30)
在方案3我得到的錯誤信息:
%d format: a number is required, not str
所以我的問題是,爲什麼在方案2中允許(在預期小數放置(S)的轉換),但反過來講在場景3中是不允許的。謝謝,我希望我儘可能地解釋我的問題。
您可以將整數轉換爲字符串,而不是相反。 –
因爲可以將小數轉換爲字符串,但不能將字符串轉換爲小數。在你的情況下,你正嘗試將'Bob'投射到%d。 – Kadir