Convert to Binary and Keep Leading Zeros
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.
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:
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:
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:
Conquering edge cases
Adaptable padding for nature's variety
When the binary length isn't written in the stars, tweak the padding:
Silencing the '0b' prefix elegantly
If you dislike getting into slicing wars with bin(x)[2:]
, tame the #
option:
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:
The righteous rjust:
While they both achieve the goal of padding, zfill
and rjust
shine in different ways.
Was this article helpful?