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

Viewed 35124

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?

6 Answers

In my case, I was trying to zero-pad a string instead of a number.

The solution was simply to convert the text to a number before applying the padding:

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