Python TypeError:传递给对象的非空格式字符串。\uuuu格式__
我最近遇到了这个TypeError异常,我发现很难调试它。我最终将其简化为一个小测试用例:Python TypeError:传递给对象的非空格式字符串。\uuuu格式__,python,python-3.x,string-formatting,Python,Python 3.x,String Formatting,我最近遇到了这个TypeError异常,我发现很难调试它。我最终将其简化为一个小测试用例: >>> "{:20}".format(b"hi") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: non-empty format string passed to object.__format__ 这个例外是什么意思?是否有更清晰的方法?
>>> "{:20}".format(b"hi")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: non-empty format string passed to object.__format__
这个例外是什么意思?是否有更清晰的方法?
字节
对象没有自己的格式
方法,因此使用对象
的默认值:
>>> 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__
对象。\uuuuu format\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
>>> '{:.0f}'.format(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: non-empty format string passed to object.__format__
>'{.0f}'。格式(无)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:传递给对象的非空格式字符串。\uuu格式__
这需要一段时间才能解决(在我的例子中,当实例变量返回None
时) 有道理,谢谢!我希望错误更直观一些!可能值得注意的是:在Python 3.4+中,这只是一个类型错误
,它会影响从对象
继承的任何内容,而不定义\uuuuuuu格式
(例如无
;类T(对象):pass
,等等)。有关背景信息,请参阅我也有这个问题,最后发现一个应该包含浮点的变量实际上包含None
。因此,“{0:.4f}”。格式(bla)
导致此异常
>>> '{!s:20s}'.format(b"Hi")
"b'Hi' "
>>> '{!s:20s}'.format(object())
'<object object at 0x1100b9080>'
>>> '{:.0f}'.format(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: non-empty format string passed to object.__format__