gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:34 25 4
gpt4 key购买 nike

将纯 f 字符串与 NoneType 对象一起使用有效:

>>> a = None
>>> f'{a}'
'None'

但是,当使用格式说明符时,它会中断---就像 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__

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

>>> '%10s' % a
' None'

这是怎么回事?我不明白为什么 f'{a:>6}' 的计算结果不是 'None'。为什么格式说明符应该打破它?

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

最佳答案

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

关于python - 带有 None 的 f 字符串格式说明符抛出 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52731672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com