Text formatting error: '=' alignment not allowed in string format specifier

Text formatting error: '=' alignment not allowed in string format specifier

以下错误信息中的'=' 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"是文本,不是数字。但是错误消息似乎与此无关。

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

这种格式是可以接受的

"{num}:03".format(num="1")

但是您指定占位符的方式 {num:03} 不是。不过,这是一个有趣的 ValueError,如果您删除 :,有趣的错误将替换为标准的 KeyError.

str.__format__ 不知道如何处理您的 03 部分。这只适用于数字:

>>> "{num:03}".format(num=1)
'001'

如果你真的想用零填充一个字符串,你可以使用rjust:

>>> "1".rjust(3, "0")
'001'

出现错误消息是因为格式说明符隐含了 '=' alignment

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.

您正试图在需要 float->3.44 的地方插入 'string->"1"。删除引号“1”,即 num=1,它将起作用

解决方法是使用 '>'(右对齐)填充,其语法为:

[[fill]align][width]

对齐为 >,填充为 0,宽度为 3

>>> "{num:0>3}".format(num="1")
'001'

问题是格式规范中有一个不同的0

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
#                                          ^^^ This one

那个零只是让 fill 默认为 0align 默认为 =

=对齐指定为:

Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. It becomes the default when ‘0’ immediately precedes the field width.

Source (Python 3 docs)

这期望参数是 int,因为字符串没有符号。所以我们只是手动将其设置为>(右对齐)的正常默认值。

另请注意,0 只是指定了 fillalign 的默认值。您可以同时更改两者或仅更改对齐方式。

>>> # fill defaults to '0', align is '>', `0` is set, width is `3`
>>> "{num:>03}".format(num=-1)
'0-1'
>>> # fill is `x`, align is '>', `0` is set (but does nothing), width is `"3"`
>>> "{num:x>03}".format(num=-1)
'x-1'
>>> # fill is `x`, align is '>', `0` is set (but does nothing), width is `"03"` (3)
>>> "{num:x>003}".format(num=-1)
'x-1'

在我的例子中,我试图用零填充 字符串 而不是数字。

解决方案是在应用填充之前将文本简单地转换为数字:

num_as_text = '23'
num_as_num = int(num_as_text)
padded_text = f'{num_as_num:03}'