Python TypeError:傳遞給對(duì)象的非空格式字符串。__format__
bytes對(duì)象沒(méi)有自己的__format__方法,因此使用默認(rèn)的from object:
>>> bytes.__format__ is object.__format__True>>> ’{:20}’.format(object())Traceback (most recent call last): File '<stdin>', line 1, in <module>TypeError: non-empty format string passed to object.__format__
這只是意味著您不能在這些格式上使用簡(jiǎn)單,無(wú)格式,未對(duì)齊的格式。顯式轉(zhuǎn)換為字符串對(duì)象(就像通過(guò)解碼bytes到一樣str)以獲取格式規(guī)范支持。
您可以使用!s字符串轉(zhuǎn)換使轉(zhuǎn)換明確:
>>> ’{!s:20s}’.format(b'Hi')'b’Hi’ '>>> ’{!s:20s}’.format(object())’<object object at 0x1100b9080>’
object.__format__明確拒絕格式字符串,以避免隱式字符串轉(zhuǎn)換,特別是因?yàn)楦袷皆O(shè)置指令是特定于類(lèi)型的。
解決方法我最近遇到了TypeError異常,發(fā)現(xiàn)它很難調(diào)試。我最終將其簡(jiǎn)化為這個(gè)小測(cè)試用例:
>>> '{:20}'.format(b'hi')Traceback (most recent call last): File '<stdin>',line 1,in <module>TypeError: non-empty format string passed to object.__format__
無(wú)論如何,這對(duì)我來(lái)說(shuō)不是很明顯。我的代碼的解決方法是將字節(jié)字符串解碼為unicode:
>>> '{:20}'.format(b'hi'.decode('ascii')) ’hi ’
此異常的含義是什么?有沒(méi)有一種方法可以使它更清晰?
相關(guān)文章:
1. python爬蟲(chóng)實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊2. Spring如何使用xml創(chuàng)建bean對(duì)象3. python實(shí)現(xiàn)在內(nèi)存中讀寫(xiě)str和二進(jìn)制數(shù)據(jù)代碼4. python實(shí)現(xiàn)PolynomialFeatures多項(xiàng)式的方法5. HTML 絕對(duì)路徑與相對(duì)路徑概念詳細(xì)6. python 利用toapi庫(kù)自動(dòng)生成api7. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法8. Android Studio設(shè)置顏色拾色器工具Color Picker教程9. Java程序的編碼規(guī)范(6)10. python實(shí)現(xiàn)讀取類(lèi)別頻數(shù)數(shù)據(jù)畫(huà)水平條形圖案例
