Given an integer n, output the no. of leading zeros in its binary form. A leading zero is any 0 digit that comes before the first nonzero digit in a number's binary form.
Use the str. zfill() Function to Display a Number With Leading Zeros in Python. The str. zfill(width) function is utilized to return the numeric string; its zeros are automatically filled at the left side of the given width , which is the sole attribute that the function takes.
All in all, when you add a zero on the left it has no effect, but when you add a zero on the right the effect is multiplication by 2. For example, consider binary strings 1, 10, 100, 1000, 1 is 1, 10 is 2, 100 is 4 and 1000 is 8.
Use the format()
function:
>>> format(14, '#010b')
'0b00001110'
The format()
function simply formats the input following the Format Specification mini language. The #
makes the format include the 0b
prefix, and the 010
size formats the output to fit in 10 characters width, with 0
padding; 2 characters for the 0b
prefix, the other 8 for the binary digits.
This is the most compact and direct option.
If you are putting the result in a larger string, use an formatted string literal (3.6+) or use str.format()
and put the second argument for the format()
function after the colon of the placeholder {:..}
:
>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'
As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using format()
:
>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format") # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193
But I'd use that only if performance in a tight loop matters, as format(...)
communicates the intent better.
If you did not want the 0b
prefix, simply drop the #
and adjust the length of the field:
>>> format(14, '08b')
'00001110'
>>> '{:08b}'.format(1)
'00000001'
See: Format Specification Mini-Language
Note for Python 2.6 or older, you cannot omit the positional argument identifier before :
, so use
>>> '{0:08b}'.format(1)
'00000001'
I am using
bin(1)[2:].zfill(8)
will print
'00000001'
You can use the string formatting mini language:
def binary(num, pre='0b', length=8, spacer=0):
return '{0}{{:{1}>{2}}}'.format(pre, spacer, length).format(bin(num)[2:])
Demo:
print binary(1)
Output:
'0b00000001'
EDIT: based on @Martijn Pieters idea
def binary(num, length=8):
return format(num, '#0{}b'.format(length + 2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With