繁体   English   中英

Python TypeError:传递给 object.__format__ 的非空格式字符串

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

我最近遇到了这个 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__

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

 >>> "{:20}".format(b"hi".decode("ascii"))
 'hi                  '

这个异常的含义是什么? 有什么办法可以说得更清楚吗?

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__

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

您可以使用!s字符串转换使转换显式:

>>> '{!s:20s}'.format(b"Hi")
"b'Hi'               "
>>> '{!s:20s}'.format(object())
'<object object at 0x1100b9080>'

object.__format__明确拒绝格式化字符串以避免隐式字符串转换,特别是因为格式化指令是特定于类型的。

尝试格式化None时也会发生这种情况:

>>> '{:.0f}'.format(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: non-empty format string passed to object.__format__

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM