Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 

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?

like image 685
bignose Avatar asked Mar 16 '16 18:03

bignose


1 Answers

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

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

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 '='.

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.

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.

like image 152
bignose Avatar answered Sep 20 '22 12:09

bignose