gpt4 book ai didi

python - 文本格式错误 : '=' alignment not allowed in string format specifier

转载 作者:IT老高 更新时间:2023-10-28 22:20:47 29 4
gpt4 key购买 nike

'='alignment在下面的错误信息中是什么意思,为什么这段代码会导致呢?

>>> "{num:03}".format(num="1")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: '=' alignment not allowed in string format specifier

代码有一个微妙的问题:输入值 "1" 是文本,而不是数字。但是错误消息似乎与此无关。

错误消息中没有任何内容表明为什么“'='对齐”是相关的,并且它没有出现在代码中。那么发出那个错误信息有什么意义呢?

最佳答案

出现错误消息是因为 '=' 对齐 已被格式说明符暗示。

str.format format spec mini-language解析器已决定对齐说明符“=”因为:

Preceding the width field by a zero ('0') character enables sign-aware zero-padding for numeric types. This is equivalent to a fill character of '0' with an alignment type of '='.

因此,通过将 0N 指定为“N 宽度的零填充”,您既暗示了“输入是数字类型”,又暗示了“零应该位于符号和数字之间”。后一种含义就是 '=' alignment 的含义。

由于值 "1" 不是数字,因此“=”对齐处理代码会引发该异常。编写该消息时希望您知道它在说什么,因为您要求(暗示)“=”对齐。

是的,我认为错误信息需要改进。我有 raised an issue for that .

关于python - 文本格式错误 : '=' alignment not allowed in string format specifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36044676/

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