bug in ''.format()
MRAB
python at mrabarnett.plus.com
Thu Nov 2 18:00:34 EDT 2017
On 2017-11-02 21:30, Ken Kundert wrote:
> I just encountered this:
>
>>>> '{:0s}'.format('hello')
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> ValueError: '=' alignment not allowed in string format specifier
>
> The exception goes away if I do not specify a width of the string:
>
>>>> '{:s}'.format('hello')
> 'hello'
>
> My reading of the documentation says I should be able to specify a width
> when interpolating a string.
>
> I have tried this in 2.7.13, 3.6.1 and 3.6.2 and it fails in all of them.
>
> Is this a bug or am I confused?
> -Ken
>
The docs say this:
"""
When no explicit alignment is given, 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 '='.
"""
It thinks that the "0" means zero-padding, etc, as explained above.
(Having an explicit width of 0 is kind of odd anyway, if you think about
it!)
The solution is to include an alignment character:
>>> '{:<0s}'.format('hello')
'hello'
More information about the Python-list
mailing list