classification
Title: Option to show leading zeros for bin/hex/oct
Type: enhancement Stage: needs patch
Components: Interpreter Core Versions: Python 3.3
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: endolith, eric.smith, mark.dickinson
Priority: normal Keywords:

Created on 2012-04-29 16:12 by endolith, last changed 2012-05-01 11:09 by eric.smith. This issue is now closed.

Messages (4)
msg159623 - (view) Author: (endolith) Date: 2012-04-29 16:12
Suggestion: Add an option to bin/hex/oct functions to format binary output with a minimum fixed width, including leading zeros.  Also might be useful for hex and oct.

Currently, bin(18) produces '0b10010'

with this change, something like bin(18, foo=8) would produce '0b00010010'


Examples of people wanting this:

http://stackoverflow.com/questions/3258330/converting-from-hex-to-binary-without-losing-leading-0s-python

http://stackoverflow.com/questions/1002116/can-bin-be-overloaded-like-oct-and-hex-in-python-2-6

http://stackoverflow.com/a/1425558/125507

https://www.linuxquestions.org/questions/programming-9/in-python-printing-leading-zero-for-hex-numbers-0-through-f-719426/
msg159624 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2012-04-29 16:15
-1. str.format already does this quite effectively;  I don't see a real need to complicate the bin, hex and oct signatures.

>>> '{:016b}'.format(324)
'0000000101000100'
>>> '{:016o}'.format(324)
'0000000000000504'
>>> '{:016x}'.format(324)
'0000000000000144'
msg159749 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2012-05-01 11:03
I'm rejecting this: the functionality is already there in str.format, and there's little to be gained by adding another way to do it.
msg159750 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2012-05-01 11:09
I agree with Mark.

This can also be done slightly more efficiently with plain format():

>>> format(324, "016b")
'0000000101000100'
>>> format(324, "016o")
'0000000000000504'
>>> format(324, "016x")
'0000000000000144'

And with either format() or str.format(), you can add the appropriate prefix:
>>> format(324, "#016b")
'0b00000101000100'
>>> format(324, "#016o")
'0o00000000000504'
>>> format(324, "#016x")
'0x00000000000144'

I don't see ever adding all of the possible options to bin(), etc.
History
Date User Action Args
2012-05-01 11:09:05eric.smithsetmessages: + msg159750
2012-05-01 11:03:34mark.dickinsonsetstatus: open -> closed

nosy: + eric.smith
messages: + msg159749

resolution: rejected
2012-04-29 16:28:20mark.dickinsonsetstage: needs patch
2012-04-29 16:17:10mark.dickinsonsetversions: + Python 3.3, - Python 2.7
2012-04-29 16:15:21mark.dickinsonsetnosy: + mark.dickinson
messages: + msg159624
2012-04-29 16:12:14endolithcreate