带 None 的 f 字符串格式说明符抛出 TypeError

rey*_*nlp 1 python string-formatting

使用带有 NoneType 对象的普通 f 字符串有效:

>>> a = None
>>> f'{a}'
'None'
Run Code Online (Sandbox Code Playgroud)

但是,当使用格式说明符时,它会中断---与 str.format() 一样:

>>> f'{a:>6}'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported format string passed to NoneType.__format__

>>> '{:>6}'.format(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported format string passed to NoneType.__format__
Run Code Online (Sandbox Code Playgroud)

出乎意料的是,(至少对我而言)旧的 C 样式字符串格式有效:

>>> '%10s' % a
'      None'
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?我不明白为什么f'{a:>6}'不评估为' None'. 为什么格式说明符要打破它?

这是python中的错误吗?如果它是一个错误,我将如何修复它?

Mar*_*nen 5

None不是字符串,所以f'{None:>6}'没有意义。您可以将其转换为字符串f'{None!s:>6}'!a!s、 和分别在对象上!r调用ascii()str()repr()