Slater Victoroff
Slater Victoroff

Reputation: 21914

How to return a number as a binary string with a set number of bits in python

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?

Upvotes: 3

Views: 4913

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1122222

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.

Upvotes: 12

Raymond Hettinger
Raymond Hettinger

Reputation: 226346

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

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

Upvotes: 3

avasal
avasal

Reputation: 14854

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'

Upvotes: 3

Related Questions