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 from Martijn Pieters on Stack Overflow
Top answer
1 of 11
368

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'
2 of 11
152
>>> '{: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'      
🌐
Stack Abuse
stackabuse.com › bytes › add-leading-zeros-to-a-number-in-python
Add Leading Zeros to a Number in Python
July 2, 2022 - The parameter to zfill is the length of the string you want to pad, not necessarily the number of zeros to add. So in the example above, if your string is already 5 characters long, it will not add any zeros. ... No spam ever. Unsubscribe anytime. Read our Privacy Policy.
🌐
Python
docs.python.org › 3 › builtins › stdtypes.html
Built-in Types — Python 3.14.7 documentation
Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including hex, octal and binary numbers) yield integers. Numeric literals containing a decimal point or an exponent sign yield floating-point numbers.
🌐
Initial Commit
initialcommit.com › blog › python-zfill-method
Python zfill Method
November 1, 2021 - >>> "512".zfill(5) '00512' >>> "64".zfill(5) '00064' This can be useful when formatting binary numbers as text since they are often represented in 32-bit or 64-bit formats. Therefore they often have a lot of leading zeros.
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to convert an integer to binary with leading zeros in python
5 Best Ways to Convert an Integer to Binary with Leading Zeros in Python - Be on the Right Side of Change
February 18, 2024 - This method first converts the integer to a binary string using bin(), then applies the zfill method. ... The code snippet converts the number 5 to binary using bin(), then slices off the “0b” prefix before padding the string with zeros ...
🌐
Finxter
blog.finxter.com › home › learn python blog › python print binary without ‘0b’
Python Print Binary Without '0b' - Be on the Right Side of Change
September 5, 2021 - In combination with slicing from the third character, you can easily construct a binary string without leading '0b' characters and with leading '0' characters up to the length passed into the string.zfill(length) method.
🌐
W3Schools
w3schools.com › python › ref_string_zfill.asp
Python String zfill() Method
a = "hello" b = "welcome to the jungle" c = "10.000" print(a.zfill(10)) print(b.zfill(10)) print(c.zfill(10)) Try it Yourself » ... Coding fundamentals as bite-sized lessons and challenges. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
LabEx
labex.io › tutorials › python-how-to-pad-binary-string-with-zeros-462156
Python - How to pad binary string with zeros
Leverage Python's string formatting capabilities · def pad_binary_left(binary_str: str, length: int = 8) -> str: """ Left pad binary string with zeros Args: binary_str: Input binary string length: Desired total length Returns: Padded binary string """ return binary_str.zfill(length) def pad_binary_right(binary_str: str, length: int = 8) -> str: """ Right pad binary string with zeros Args: binary_str: Input binary string length: Desired total length Returns: Padded binary string """ return binary_str.ljust(length, '0') class BinaryPadder: @staticmethod def pad(binary_str: str, length: int = 8,
🌐
GeeksforGeeks
geeksforgeeks.org › python-string-zfill
Python String zfill() - GeeksforGeeks
January 2, 2025 - The zfill(3) method pads the string with two zeros on the left to make its total length 3.
Find elsewhere
🌐
Tutorialspoint
tutorialspoint.com › python › string_zfill.htm
Python String zfill() Method
The Python String zfill() method is used to fill the string with zeroes on its left until it reaches a certain width; else called Padding. If the prefix of this string is a sign character (+ or -), the zeroes are added after the sign character
🌐
Note.nkmk.me
note.nkmk.me › home › python
Pad Strings and Numbers with Zeros in Python (Zero-padding) | note.nkmk.me
May 18, 2023 - To pad an integer with zeros, first convert it to a string using str(), then call zfill().
🌐
Codecademy
codecademy.com › docs › python › strings › .zfill()
Python | Strings | .zfill() | Codecademy
November 19, 2023 - Returns a string with zeros padding the left side based on the integer given.
🌐
docs.python.org
docs.python.org › 3 › library › stdtypes.html
Built-in Types — Python 3.13.5 documentation
The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some colle...
🌐
Beautiful Soup
tedboy.github.io › python_stdlib › generated › generated › __builtin__.bytes.zfill.html
__builtin__.bytes.zfill — Python Standard Library
__builtin__.bytes.zfill · View page source · bytes.zfill(width) → string¶ · Pad a numeric string S with zeros on the left, to fill a field of the specified width.
🌐
Real Python
realpython.com › ref › builtin-functions › bin
bin() | Python’s Built-in Functions – Real Python
Say you need to manipulate colors in hexadecimal and RGB (red, green, blue) formats. You can use bin() to break this color down into its individual red, green, and blue components in binary form: Language: Python · >>> def rgb_to_bin(rgb_color): ... red = bin(rgb_color[0])[2:].zfill(8) ...
🌐
Codemia
codemia.io › home › knowledge hub › convert int to binary string in python
Convert int to binary string in Python | Codemia
January 9, 2025 - The format specifier 08b means: pad with zeros to 8 characters wide, format as binary. This is more readable and reliable than manually prepending zeros with zfill(): ... 1# Works, but less clear than the format specifier 2print(bin(13)[2:].zfill(8)) # '00001101' 3 4# Preferred: the intent is obvious 5print(f'{13:08b}') # '00001101' This is where most developers get confused. Python integers are arbitrary precision, so there is no fixed bit width.
🌐
Python Pool
pythonpool.com › home › tutorials › python zfill(): zero-pad strings, numbers, and signs
Python zfill(): Zero-Pad Strings, Numbers, and Signs
July 13, 2026 - Quick answer: zfill(width) returns a new string padded with zeros on the left. If the string begins with + or -, Python places the zeros after the sign.