The Python Oracle

Convert to binary and keep leading zeros

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles

--

Chapters
00:00 Question
00:33 Accepted answer (Score 327)
02:16 Answer 2 (Score 141)
02:44 Answer 3 (Score 43)
02:59 Answer 4 (Score 11)
03:39 Thank you

--

Full question
https://stackoverflow.com/questions/1692...

Accepted answer links:
[format()]: http://docs.python.org/2/library/functio...
[Format Specification mini language]: http://docs.python.org/2/library/string....
[formatted string literal]: https://docs.python.org/3/reference/lexi...
[str.format()]: https://docs.python.org/2/library/stdtyp...

Answer 2 links:
[Format Specification Mini-Language]: https://docs.python.org/2/library/string...

Answer 4 links:
[f-strings]: https://docs.python.org/3/reference/lexi...
[string formatting]: https://docs.python.org/3/library/string...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #binary #formatting #bitwiseoperators

#avk47



ACCEPTED ANSWER

Score 356


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'



ANSWER 2

Score 148


>>> '{: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'      



ANSWER 3

Score 53


I am using

bin(1)[2:].zfill(8)

will print

'00000001'



ANSWER 4

Score 10


You can use the string formatting mini language (Thanks to @Martijn Pieters for the suggestion) idea:

def binary(num, length=8):
    return format(num, '#0{}b'.format(length + 2))

Demo:

print(binary(1))

Output:

'0b00000001'