gpt4 book ai didi

没有转换说明符的 Python 不会在 % 上引发异常

转载 作者:太空狗 更新时间:2023-10-30 03:00:38 25 4
gpt4 key购买 nike

描述了用于字符串格式化的 % 运算符 here .

通常,当出现一个没有转换说明符的字符串时,它会抛出一个 TypeError: not all arguments converted during string formatting。 .例如,"" % 1将失败。到目前为止,还不错。

但有时,如果 % 运算符右侧的参数为空,它不会失败:"" % [] , 或 "" % {}"" % ()将默默地返回空字符串,看起来很公平。

"%s"相同instead of the empty string 会将空对象转换为字符串,除了最后一个会失败,但我认为这是 % 运算符问题的一个实例,由 format 解决方法。

还有非空字典的情况,比如"" % {"a": 1} ,这是有效的,因为它确实应该与命名类型说明符一起使用,例如 "%(a)d" % {"a": 1} .

但是,有一种情况我不明白:"" % b"x"将返回空字符串,不会引发异常。为什么?

最佳答案

我不是 100% 确定,但在快速查看 sources 之后,我猜原因如下:

% 右边只有一个参数时,Python 会查看它是否有 getitem 方法,如果有,则假定它是一个映射并期望我们使用像 %(name)s 这样的命名格式。否则,Python 从参数创建一个单元素元组并执行位置格式化。不使用映射检查参数计数,因此,由于 byteslists 确实有 getitem,它们不会失败:

>>> "xxx" % b'a'
'xxx'
>>> "xxx" % ['a']
'xxx'

同时考虑:

>>> class X: pass
...
>>> "xxx" % X()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

>>> class X:
... def __getitem__(self,x): pass
...
>>> "xxx" % X()
'xxx'

字符串是这个规则的异常(exception)——它们有 getitem,但对于位置格式仍然是“双倍化”的:

>>> "xxx" % 'a'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

当然,这种“序列作为映射”的逻辑没有多大意义,因为格式化键总是字符串:

>>> "xxx %(0)s" % ['a']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str

但我怀疑有人会解决这个问题,因为 % 无论如何都被放弃了。

关于没有转换说明符的 Python 不会在 % 上引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28560482/

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