This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: String formatting produces incorrect result with left-aligned zero-padded format
Type: Stage:
Components: Interpreter Core Versions:
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: eric.smith, mrabarnett, serhiy.storchaka
Priority: normal Keywords:

Created on 2018-12-20 14:41 by serhiy.storchaka, last changed 2022-04-11 14:59 by admin.

Messages (3)
msg332231 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2018-12-20 14:41
Compare printf-style string formatting and new-style string formatting.

>>> '%-020d' % 42
'42                  '
>>> format(42, '<020')
'42000000000000000000'
>>> format(42, '<020d')
'42000000000000000000'
>>> '%-020x' % 42
'2a                  '
>>> format(42, '<020x')
'2a000000000000000000'
>>> '%-020g' % 1.2e-8
'1.2e-08             '
>>> format(1.2e-8, '<020')
'1.2e-080000000000000'
>>> format(1.2e-8, '<020g')
'1.2e-080000000000000'
>>> format(1.2e-8, '<020e')
'1.200000e-0800000000'

New-style string formatting produces the result that looks like a correctly formatted number, but it represents incorrect number.

I think that zero padding should not be allowed for left-aligned format for numbers (except the 'f' format). Zero padding is already disallowed for complex numbers.
msg332244 - (view) Author: Matthew Barnett (mrabarnett) * (Python triager) Date: 2018-12-20 18:11
A similar issue exists with centring:

>>> format(42, '^020')
'00000000042000000000'
msg332265 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2018-12-20 21:41
I think this falls in to the consenting adults category. You can also do things like:
>>> format(42, '->3')
'-42'

But why bother preventing this?

It is unfortunate that %-formatting and .__format__() are different in this regard, but at this point I wouldn't recommend making any changes.
History
Date User Action Args
2022-04-11 14:59:09adminsetgithub: 79727
2018-12-20 21:41:18eric.smithsetmessages: + msg332265
2018-12-20 18:11:09mrabarnettsetnosy: + mrabarnett
messages: + msg332244
2018-12-20 14:41:00serhiy.storchakacreate