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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:08:10  来源:igfitidea点击:

Python TypeError: non-empty format string passed to object.__format__

pythonpython-3.xstring-formatting

提问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:

无论如何,这对我来说非常不明显。我的代码的解决方法是将字节字符串解码为 un​​icode:

 >>> "{: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

bytesobjects do not have a __format__method of their own, so the default from objectis 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 bytesto str) to get format spec support.

这只是意味着除了直接的、未格式化的未对齐格式之外,您不能使用任何其他内容。显式转换为字符串对象(就像您通过解码bytesstr)以获得格式规范支持

You can make the conversion explicit by using the !sstring 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 Nonewas being returned by an instance variable)!

这花了一些时间来解决(在我的情况下,什么时候None被实例变量返回)!