Python TypeError:传递给 object.__format__ 的非空格式字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24170519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python TypeError: non-empty format string passed to object.__format__
提问by Chris AtLee
I hit this TypeError exception recently, which I found very difficult to debug. I eventually reduced it to this small test case:
我最近遇到了这个 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__
This is very non-obvious, to me anyway. The workaround for my code was to decode the byte string into unicode:
无论如何,这对我来说非常不明显。我的代码的解决方法是将字节字符串解码为 unicode:
>>> "{:20}".format(b"hi".decode("ascii"))
'hi '
What is the meaning of this exception? Is there a way it can be made more clear?
这个异常的含义是什么?有什么办法可以说得更清楚吗?
采纳答案by Martijn Pieters
bytes
objects do not have a __format__
method of their own, so the default from object
is used:
bytes
对象没有自己的__format__
方法,所以使用默认的 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__
It just means that you cannot use anything other than straight up, unformatted unaligned formatting on these. Explicitly convert to a string object (as you did by decoding bytes
to str
) to get format spec support.
这只是意味着除了直接的、未格式化的未对齐格式之外,您不能使用任何其他内容。显式转换为字符串对象(就像您通过解码bytes
为str
)以获得格式规范支持。
You can make the conversion explicit by using the !s
string conversion:
您可以使用!s
字符串转换使转换显式:
>>> '{!s:20s}'.format(b"Hi")
"b'Hi' "
>>> '{!s:20s}'.format(object())
'<object object at 0x1100b9080>'
object.__format__
explicitly rejects format strings to avoid implicit string conversions, specifically because formatting instructions are type specific.
object.__format__
显式拒绝格式字符串以避免隐式字符串转换,特别是因为格式指令是特定于类型的。
回答by Jeremy Field
This also happens when trying to format None
:
尝试格式化时也会发生这种情况None
:
>>> '{:.0f}'.format(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: non-empty format string passed to object.__format__
That took a moment to work out (in my case, when None
was being returned by an instance variable)!
这花了一些时间来解决(在我的情况下,什么时候None
被实例变量返回)!