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__
這只是意味著您不能在這些格式上使用簡單,無格式,未對(duì)齊的格式。顯式轉(zhuǎn)換為字符串對(duì)象(就像通過解碼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)試。我最終將其簡化為這個(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__
無論如何,這對(duì)我來說不是很明顯。我的代碼的解決方法是將字節(jié)字符串解碼為unicode:
>>> '{:20}'.format(b'hi'.decode('ascii')) ’hi ’
此異常的含義是什么?有沒有一種方法可以使它更清晰?
相關(guān)文章:
1. 關(guān)于WPF WriteableBitmap類直接操作像素點(diǎn)的問題2. JavaScript前端中的偽類元素before和after使用詳解3. ASP基礎(chǔ)入門第一篇(ASP技術(shù)簡介)4. asp取整數(shù)mod 有小數(shù)的就自動(dòng)加15. 源碼分析MinimalApi是如何在Swagger中展示6. PHP laravel實(shí)現(xiàn)基本路由配置詳解7. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過程(親測(cè)可用)8. 熊海CMS代碼審計(jì)漏洞分析9. PHP JSAPI調(diào)支付API實(shí)現(xiàn)微信支付功能詳解10. 表單中Readonly和Disabled的區(qū)別詳解
