在 Python 中修复 TypeError: Non-Empty Format String Passed to Object.__format__

Python中的format()方法允许您替换变量并执行数据格式化。此方法不用于处理以下输入以外的任何输入:

  • 表示为s的字符串
  • 十进制表示为d
  • 浮点表示为f
  • 字符表示为c
  • 八进制表示为o
  • 十六进制表示为x
  • 二进制表示为b
  • 指数表示为e

如果任何其他数据类型访问该方法,解释器将引发以下错误:

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

在 Python 中修复 TypeError: Non-Empty Format String Passed to Object.__format__

假设我们尝试在没有此方法的数据类型上调用format()方法,例如byte数据类型。解释器将引发错误,因为byte类型对象没有format()方法。

在下面的代码中,我们特意调用了数据类型为format()byte方法。

示例代码:

#Python 3.x
'{:10}'.format(b'delftstack')

输出:

#Python 3.x
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-1909c614b7f5> in <module>()
----> 1 '{:10}'.format(b'delftstack')
TypeError: unsupported format string passed to bytes.__format__

此错误的解决方案是将数据类型从字节显式转换为字符串。我们将使用!s符号进行转换。

示例代码:

#Python 3.x
s='{!s:10s}'.format(b"delftstack")
print(s)

输出:

#Python 3.x
b'delftstack'

当我们尝试格式化TypeError: non-empty format string passed to object.__format__时,也会引发None

示例代码:

#Python 3.x
'{:.0f}'.format(None)

输出:

#Python 3.x
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-89103a1332e2> in <module>()
----> 1 '{:.0f}'.format(None)
TypeError: unsupported format string passed to NoneType.__format__

解决方案是传递一个有效的数据类型而不是None

示例代码:

#Python 3.x
s='{!s:10s}'.format(b"delftstack")
print(s)

输出:

#Python 3.x
b'delftstack'