Explain Codes LogoExplain Codes Logo

Convert to Binary and Keep Leading Zeros

python
string-formatting
f-strings
binary-conversion
Nikita BarsukovbyNikita Barsukov·Feb 3, 2025
TLDR

When it comes to keeping leading zeros in binary, the format() function is your best friend. Use '{:08b}'.format(number) and customize the 08 to your desired binary string length.

binary_padded = '{:08b}'.format(5) print(binary_padded) # Outputs: '00000101' because 5 in binary is cool that way

Formatted string literals (f-strings)

From Python 3.6 onwards, formatted string literals, or f-strings as they are fondly called, offer a more readable syntax for string formatting:

number = 5 binary_padded = f"{number:08b}" print(binary_padded) # Output: '00000101', still holding strong with leading zeroes!

Note the use of 08b here to demand an 8-digit binary number.

The Format specification mini-language

The format specification mini-language gets some serious work done when it comes to handling string formatting needs easily:

number = 5 width = 8 binary_padded = format(number, f'#0{width + 2}b')[2:] print(binary_padded) # Output: '00000101', without 0b shouting at your face

It slices off the 0b prefix to present you with the nicely packed result you want.

Some attention on performance

When the objective is melting the seconds, consider using f-strings or the format function directly. Turns out they're often quicker than their predecessor, the % formatting.

Looking back at Python 2

For those nostalgic of Python 2, append 0 to your format string:

binary_padded = '{0:08b}'.format(5) print(binary_padded) # Compatible with Python 2.x, Output: '00000101'

Conquering edge cases

Adaptable padding for nature's variety

When the binary length isn't written in the stars, tweak the padding:

numbers = [5, 50, 500] binaries_padded = ['{:08b}'.format(num).rjust(max_length, '0') for num in numbers] print(binaries_padded) # Creates a pretty little list of 8-bit binaries, led by zeros

Silencing the '0b' prefix elegantly

If you dislike getting into slicing wars with bin(x)[2:], tame the # option:

binary_clean = format(number, '#010b')[2:] print(binary_clean) // All cleaned up and '0b' removed: '00000101'

Introducing zfill and rjust: Your new binary friends

Meet zfill and rjust, a pair of string methods ready to pad your binary strings when the road gets rough:

zfill to the rescue:

binary_zfilled = bin(5)[2:].zfill(8) print(binary_zfilled) // Why hello '00000101', looking filled up with zeros!

The righteous rjust:

binary_rjusted = bin(5)[2:].rjust(8, '0') print(binary_rjusted) // Output: '00000101', leading the way with zeros. Way to go!

While they both achieve the goal of padding, zfill and rjust shine in different ways.