Besides going through string formatting, it is interesting to have in mind that when working with numbers and their hexadecimal representation we usually are dealing with byte-content, and interested in how bytes relate.
The bytes
class in Python 3 had been enriched with methods over the 3.x series, and int.to_bytes
combined with the bytes.hex()
provide full control of the hex-digits output, while preserving the semantics of the transform (not to mention, holding the intermediate "bytes" object ready to be used in any binary protocol that requires the number):
In [8]: i = 3735928559
In [9]: i.to_bytes(4, "big").hex()
Out[9]: 'deadbeef'
Besides that, bytes.hex()
allow some control over the output, such as specifying a separator for the hex digits:
In [10]: bytes.hex?
Docstring:
Create a string of hexadecimal numbers from a bytes object.
sep
An optional single character or byte to separate hex bytes.
bytes_per_sep
How many bytes between separators. Positive values count from the
right, negative values count from the left.
Example:
>>> value = b'\xb9\x01\xef'
>>> value.hex()
'b901ef'
>>> value.hex(':')
'b9:01:ef'
>>> value.hex(':', 2)
'b9:01ef'
>>> value.hex(':', -2)
'b901:ef'
(That said, in most scenarios just a quick print is wanted, I'd probably just go through f-string formatting, as in the accepted answer: f"{mynumber:04x}"
- for the simple reason of "less things to remember")