我正在學習 Python the Hard Way 練習 24,同時將他們在書中使用的所有舊樣式格式 (%) 轉換為我喜歡的新樣式 (.format())。正如你在下面的代碼中看到的,如果我分配一個變量“p”,我可以成功地解包函數返回的元組值。但是當我直接使用該返回值時,它會拋出一個 TypeError。def secret_formula(started): jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 return jelly_beans, jars, cratesstart_point = 10000#Old styleprint("We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point))#New style that worksprint("We'd have {p[0]:.0f} beans, {p[1]:.0f} jars, and {p[2]:.0f} crates.".format(p=secret_formula(start_point)))#This doesn't work:print("We'd have {0:.0f} beans, {1:.0f} jars, and {2:.0f} crates.".format(secret_formula(start_point)))拋出錯誤:Traceback (most recent call last): File "ex.py", line 16, in <module> print("We'd have {0:.0f} beans, {1:.0f} jars, and {2:.0f} crates.".format(secret_formula(start_point))) TypeError: unsupported format string passed to tuple.__format__有人可以解釋為什么在 .format() 中直接使用函數不起作用嗎?如何將其轉換為 f 字符串?
2 回答

神不在的星期二
TA貢獻1963條經驗 獲得超6個贊
將secret_formulato的返回值按format位置傳遞并不比通過關鍵字傳遞更直接。無論哪種方式,您都將返回值作為單個參數傳遞。
要訪問參數的元素,當你將它作為p關鍵字參數,使用p[0],p[1]和p[2]。同樣,經過論證位置上的時候,你就必須訪問元素0[0],0[1]和0[2],指定位置0。(這是專門str.format處理格式占位符的方式,而不是正常的 Python 索引語法):
print("We'd have {0[0]:.0f} beans, {0[1]:.0f} jars, and {0[2]:.0f} crates.".format(
secret_formula(start_point)))
但是,使用解壓縮返回值*,將元素作為單獨的參數傳遞會更簡單和更傳統:
print("We'd have {0:.0f} beans, {1:.0f} jars, and {2:.0f} crates.".format(
*secret_formula(start_point)))
添加回答
舉報
0/150
提交
取消