I thought f"0x{number:04x}"
produces a hex number with four digits. But I recently noticed that this is not the case:
f"0x{13544123:04x}" = "0xceaabb"
which has 6 digits. What am I doing wrong here?
The key thing to understand here is that :04x
in the f-string formatting means at least four digits, but not exactly four digits. If the number in question is larger than can be represented in the number of digits specified, it will display as many digits as needed.
I think it's easier to understand this if we try to express two numbers in four digits in base 10:
x = 999999
y = 1
f"y is {y:04d} and x is {x:04d}"
# 'y is 0001 and x is 999999'
1
becomes 0001
. However, there is no way to express 999999
in four digits. Similarly, 13544123
in base 10 is 0xceaabb
in hex, which cannot be expressed in four digits.