问题描述
我最近遇到了这个 TypeError 异常,我发现它很难调试.我最终将其简化为这个小测试用例:
>>>"{:20}".format(b"hi")回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:传递给 object.__format__ 的非空格式字符串无论如何,这对我来说非常不明显.我的代码的解决方法是将字节字符串解码为 unicode:
>>>"{:20}".format(b"hi".decode("ascii"))'你好 '
这个异常是什么意思?有什么方法可以说得更清楚吗?
bytes
对象没有自己的 __format__
方法,所以默认来自 使用对象
:
这只是意味着除了直接的、未格式化的未对齐格式之外,您不能使用任何其他格式.显式转换为字符串对象(就像您通过将 bytes
解码为 str
所做的那样)以获取 格式规范支持.
您可以使用 !s
字符串转换使转换显式:
object.__format__
明确拒绝格式化字符串以避免隐式字符串转换,特别是因为格式化指令是特定于类型的.
I hit this TypeError exception recently, which I found very difficult to debug. I eventually reduced it to this small test case:
>>> "{: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:
>>> "{:20}".format(b"hi".decode("ascii"))
'hi '
What is the meaning of this exception? Is there a way it can be made more clear?
bytes
objects do not have a __format__
method of their own, so the default from object
is used:
>>> 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.
You can make the conversion explicit by using the !s
string conversion:
>>> '{!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.
这篇关于Python TypeError:传递给 object.__format__ 的非空格式字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!