Convert to binary and keep leading zeros in Python

I'm trying to convert an integer to binary using the bin() function in Python. However, it always removes the leading zeros, which I actually need, such that the result is always 8-bit:


    bin(1) -> 0b1

    # What I would like:
    bin(1) -> 0b00000001

Is there a way of doing this?

Use the format() function:

    >>> format(14, '#010b')

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 str.format() and put the second argument for the format() function after the colon of the placeholder {:..}:

    >>> 'The produced output, in binary, is: {:#010b}'.format(14)
    'The produced output, in binary, is: 0b00001110'

If you did not want the 0b prefix, simply drop the # and adjust the length of the field:

    >>> format(14, '08b')