Python TypeError:傳遞給對(duì)象的非空格式字符串。__format__
bytes對(duì)象沒有自己的__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è)置指令是特定于類型的。
解決方法我最近遇到了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 ’
此異常的含義是什么?有沒有一種方法可以使它更清晰?
相關(guān)文章:
1. PHP laravel實(shí)現(xiàn)導(dǎo)出PDF功能2. JavaScript實(shí)現(xiàn)留言板實(shí)戰(zhàn)案例3. 使用Blazor框架實(shí)現(xiàn)在前端瀏覽器中導(dǎo)入和導(dǎo)出Excel4. ASP基礎(chǔ)知識(shí)Command對(duì)象講解5. python中文本字符處理的簡(jiǎn)單方法記錄6. 資深程序員:給Python軟件開發(fā)測(cè)試的25個(gè)忠告!7. Python-openpyxl表格讀取寫入的案例詳解8. 如何從Python的cmd中獲得.py文件參數(shù)9. Python基于requests庫(kù)爬取網(wǎng)站信息10. vscode運(yùn)行php報(bào)錯(cuò)php?not?found解決辦法

網(wǎng)公網(wǎng)安備