Starting with Python 3.6, you can:

>>> value = 42
>>> padding = 6
>>> f"{value:#0{padding}x}"
'0x002a'

Note the padding includes the 0x. If you don't want that you can do

>>> f"0x{value:0{padding}x}"
'0x00002a'

for older python versions use the .format() string method:

>>> "{0:#0{1}x}".format(42,6)
'0x002a'

Explanation:

{   # Format identifier
0:  # first parameter
#   # use "0x" prefix
0   # fill with zeroes
{1} # to a length of n characters (including 0x), defined by the second parameter
x   # hexadecimal number, using lowercase letters for a-f
}   # End of format identifier

If you want the letter hex digits uppercase but the prefix with a lowercase 'x', you'll need a slight workaround:

>>> '0x{0:0{1}X}'.format(42,4)
'0x002A'
Answer from Tim Pietzcker on Stack Overflow
Discussions

How can I get the "format" function to leave my leading ZEROs in place?
I have some binary data that I want to hash. Specifically I am hashing a 128 bit private key. But for the discussion let’s just use a 16 bit private key. So here is my code and it works great except when my private key … More on discuss.python.org
🌐 discuss.python.org
4
0
September 23, 2023
Python , Printing Hex removes first 0? - Stack Overflow
Its ignoring the leading zeros because they mean nothing towards the decimal value of the hex values. They indicate the number of bytes the values takes up. 15 = f. 0f = 15 because 0 + 15 is 15 2018-01-03T15:04:49.9Z+00:00 ... use a format string "%2x" tells it to format it to be 2 characters wide, likewise "x" tells it to pad with ... More on stackoverflow.com
🌐 stackoverflow.com
Python Binary to hex conversion preserving leading zeroes - Stack Overflow
Added: the format string '%.*x' means "format as hexadecimal to a length as per supplied parameter, with leading zeros". More on stackoverflow.com
🌐 stackoverflow.com
July 29, 2016
[2021 Day 16] Help on turning hex into binary?

You should not always have leading zeroes, such as if the first character of the input is F.

More on reddit.com
🌐 r/adventofcode
5
2
December 19, 2021
🌐
Python.org
discuss.python.org › python help
How can I get the "format" function to leave my leading ZEROs in place? - Python Help - Discussions on Python.org
September 23, 2023 - I have some binary data that I want to hash. Specifically I am hashing a 128 bit private key. But for the discussion let’s just use a 16 bit private key. So here is my code and it works great except when my private key begins with leading zero’s. Specifically 4 leading zeros or more.
🌐
Python
bugs.python.org › issue14694
Issue 14694: Option to show leading zeros for bin/hex/oct - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/58899
🌐
LinuxQuestions.org
linuxquestions.org › questions › programming-9 › in-python-printing-leading-zero-for-hex-numbers-0-through-f-719426
In Python, printing leading zero for hex numbers 0 through f
April 15, 2009 - Hello, This is probably a simple question for an experienced Python person: This is a little python program that gets 3 random hex numbers and prints
🌐
LabEx
labex.io › tutorials › python-how-to-pad-hex-values-in-python-502158
How to pad hex values in Python | LabEx
graph TD A[Hex Value] --> B[16 Possible Digits] B --> C[0-9] B --> D[A-F] A --> E[Prefixed with 0x] A --> F[Case Insensitive] ... By understanding hex basics, you'll be well-prepared for more advanced Python programming techniques. LabEx recommends practicing these conversions to build proficiency. Hex padding ensures consistent length and formatting of hexadecimal values, which is crucial in various programming scenarios. ## Basic padding value = 15 padded_hex = f'{value:04x}' ## Zero-padded to 4 characters print(padded_hex) ## Outputs: 000f
🌐
Finxter
blog.finxter.com › home › learn python blog › python integer to hex — the ultimate guide
Python Integer to Hex - The Ultimate Guide - Be on the Right Side of Change
March 23, 2023 - In this example, the int_to_hex_color function converts the given integer to a 6-digit hexadecimal color string by using the format string "{:06x}", which ensures that the output has exactly 6 digits with leading zeros, if necessary.
Find elsewhere
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
convert number to length-specified hex string - Raspberry Pi Forums
October 23, 2012 - string = "x" % nx: format an integer as a lower-case hex string, at least four characters, with leading zeros. This is the 'official' method I knew I must be looking for but I would not have stumbled across it in a million years. The command structure itself gives no clue as to what it does, ...
🌐
Quora
quora.com › In-Python-how-do-I-use-hex-value-to-print-a-hexadecimal-String-with-0-s-padded-to-the-left-and-without-0X-in-front
In Python: how do I use hex (value) to print a hexadecimal String with 0’s padded to the left and without “0X” in front? - Quora
Answer (1 of 4): Lukas has already given you an excellent answer, but, for completeness, I feel obliged to point out that you can print hex in a somewhat more flexible way using str.format() as below where the 0 is the fill character, 6 is the field width and X says you want hex format in upperca...
🌐
Python
mail.python.org › pipermail › tutor › 2004-December › 034111.html
[Tutor] Leading zero for hex numbers - Python mailing list
December 16, 2004 - On Wed, 15 Dec 2004 17:47:58 -0800 ... print a leading 0 for hex > numbers, but it only > seems to work for for decimal numbers. > > print "0x%0X" % 12345 > > displays > 0x3039 > > instead of 0x03039 > > The Python docs state > The conversion will be zero padded for numeric ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-add-leading-zeros-to-a-number-in-python
How to Add leading Zeros to a Number in Python - GeeksforGeeks
July 23, 2025 - The string itself can be prepared similarly to how str.format would be used (). F-strings offer a clear and practical method for formatting python expressions inside of string literals. ... One approach that is not mentioned in the article is using the rjust() method of the built-in str class to add leading zeros to a number. The rjust() method returns a right-justified string, with optional padding, based on a specified width.
🌐
pythontutorials
pythontutorials.net › blog › how-can-i-format-an-integer-to-a-two-digit-hex
How to Format an Integer as Two-Digit Hex in Python: Adding Leading Zeros for Hex String Concatenation — pythontutorials.net
The built-in format() function is versatile for string formatting. For hex, use the x (lowercase) or X (uppercase) specifier, combined with 02 to enforce two digits and leading zeros.
🌐
Medium
medium.com › vicipyweb3 › mastering-leading-zero-magic-a-friendly-guide-to-formatting-leading-zeros-in-python-3cb934d7aa4f
Mastering Leading Zero Magic: A Friendly Guide to Formatting Leading Zeros in Python | by PythonistaSage | ViciPyWeb3 | Medium
May 3, 2023 - We offer a series of blog posts about python made in an easy way for all levels of developers in order to understand difficult subjects so you can go from zero to hero in web3. ... When working with Python, you’ll often encounter situations where you need to format numbers, particularly when dealing with data like dates, IDs, or rankings. In this tutorial, we’ll explore the magic of formatting numbers with leading zeros using three popular methods: f-strings, the str.format() method, and the str.zfill() method.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Format Strings and Numbers in Python: format() | note.nkmk.me
May 18, 2023 - Zero-padding · Leading sign prefix: +, space · Separator: ,, _ Binary, octal, hexadecimal: b, o, x, X · Fixed-point notation: f, F · Scientific notation: e, E · General format: g, G · Percentage: % Date and time (datetime) Note that f-strings were introduced in Python 3.6 as a more concise way of using str.format().
🌐
Finxter
blog.finxter.com › home › learn python blog › python print hex without ‘0x’
Python Print Hex Without '0x' - Be on the Right Side of Change
July 31, 2022 - The Python string.zfill() method fills the string from the left with '0' characters. In combination with slicing from the third character, you can easily construct a hexadecimal string without leading '0x' characters and with leading '0' characters up to the length passed into the ...
🌐
Finxter
blog.finxter.com › home › learn python blog › f-string python hex, oct, and bin: efficient number conversions
F-String Python Hex, Oct, and Bin: Efficient Number Conversions - Be on the Right Side of Change
March 27, 2023 - The number 8 indicates the minimum width, and leading zeros are used to fill any remaining space. This ensures that binary values are displayed with a consistent width, making the output easier to read.
🌐
Reddit
reddit.com › r/adventofcode › [2021 day 16] help on turning hex into binary?
r/adventofcode on Reddit: [2021 Day 16] Help on turning hex into binary?
December 19, 2021 -

My code for turning hexadecimal into binary works well, but I can't understand when I should have leading zeroes like the example shows. Here are some examples of what I got.

def hexadecimal_to_binary(hex):
  integer = int(hex, 16)
  binary = format(integer, "0>42b")
  return binary
#example one, need to remove all leading zeroes
print(hexadecimal_to_binary("D2FE28"))
>> 000000000000000000110100101111111000101000

#example two, needs two leading zeroes it doesn't have
print(hexadecimal_to_binary("38006F45291200"))
>> 111000000000000110111101000101001010010001001000000000 

I think I have the rest of my code pretty close to correct, I'm just struggling on this part. Could you help me out?