文本格式错误:字符串格式说明符中不允许使用“="对齐 [英] Text formatting error: '=' alignment not allowed in string format specifier

查看:70
本文介绍了文本格式错误:字符串格式说明符中不允许使用“="对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What does '=' alignment mean in the following error message, and why does this code cause it?

>>> "{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" 是文本,而不是数字.但错误消息似乎与此无关.

The code has a subtle problem: the input value "1" is text, not a number. But the error message doesn't appear to have anything to do with that.

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

Nothing in the error message indicates why "'=' alignment" is relevant, and it does not appear in the code. So what is the significance of emitting that error message?

推荐答案

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

The error message occurs because '=' alignment has been implied by the format specifier.

str.format 格式规范迷你语言 解析器决定了对齐说明符="因为:

The str.format format spec mini-language parser has decided on the alignment specifier "=" because:

在宽度字段前面加上一个零 ('0') 字符可以启用数字类型的符号感知零填充.这相当于一个用对齐类型 '=' 填充字符 '0'.

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 的含义.

So by specifying 0N as the "zero-padding to N width", you have implied both "the input is a numeric type", and "the zeros should go between the sign and the digits". That latter implication is what is meant by '=' alignment.

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

Since the value "1" is not numeric, the "="-alignment handling code raises that exception. The message is written expecting you know what it's talking about because you requested (by implication) the "=" alignment.

是的,我认为该错误消息需要改进.我已经为此提出了一个问题.

Yes, I think that error message needs to be improved. I've raised an issue for that.

这篇关于文本格式错误:字符串格式说明符中不允许使用“="对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆