3

Probably a silly question, but in python is there a simple way to automatically pad a number with zeros to a fixed length? I wasn't able to find this in the python docs, but I may not have been looking hard enough? e.i. I want bin(4) to return 00100, rather than just 100. Is there a simple way to ensure the output will be six bits instead of three?

1
  • 1
    Have a look here Commented Nov 28, 2012 at 7:12

3 Answers 3

12

Strings have a .zfill() method to pad it with zeros:

>>> '100'.zfill(5)
'00100'

For binary numbers however, I'd use string formatting:

>>> '{0:05b}'.format(4)
'00100'

The :05b formatting specification formats the number passed in as binary, with 5 digits, zero padded. See the Python format string syntax. I've used str.format() here, but the built-in format() function can take the same formatting instruction, minus the {0:..} placeholder syntax:

>>> format(4, '05b')
'00100'

if you find that easier.

Sign up to request clarification or add additional context in comments.

9 Comments

Ah, fantastic! Just what I was looking for. Bonus points for including both solutions, which is why once this one is accepted over others.
@SlaterTyranus: bin/zfill is slightly faster than format in my measurements.
@J.F.Sebastian: I see no measurements for format(), only str.format(). str.format() requires a parsing step, then filling the slots, which internally then uses format(). To compare with bin/zfill, you need to not incur that extra cost.
@MartijnPieters: yes. My older comment uses "".format that hints at that. Though I don't know what is "fair" translation of: "{:0{}b}".format(n, len(data)*8) (it is compared against bin(n)[2:].zfill(len(data)*8)) using only format() e.g., format(n, "0%db" % (len(data)*8)) has performed worse.
@J.F.Sebastian: The length cannot be pre-computed? Why not compare bin()/zfill() and format() with a fixed length?
|
3

try this...

In [11]: x = 1

In [12]: print str(x).zfill(5)
00001

In [13]: bin(4)
Out[13]: '0b100'

In [14]: str(bin(4)[2:]).zfill(5)
Out[14]: '00100'

1 Comment

+1 for using [2:] to strip the '0b' off the binary literal. that caught me at first.
3

This is a job for the format built-in function:

>>> format(4, '05b')
'00100'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.