亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 .format() 中使用函數時出現類型錯誤

在 .format() 中使用函數時出現類型錯誤

呼啦一陣風 2021-07-29 15:23:47
我正在學習 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)))


查看完整回答
反對 回復 2021-08-03
  • 2 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號