I'm attempting to output an integer as a hex with 0 padding AND center it.
data = 10
I can do one or the other:
'{:#04x}'.format(data) # my attempt at PADDING
'{:^#14x}'.format(data) # Centers Correctly
I can't figure out how to combine the two the Output I want is:
0x0a # centered in a width of 14
With Python<3.6:
>>> '{:^14s}'.format('{:#04x}'.format(data))
' 0x0a '
Python 3.6+ with an f string:
>>> '{:^14s}'.format(f'0x{data:02x}')
' 0x0a '
Which can be (perhaps abusively) shortened to:
>>> f'{f"0x{data:02x}":^14}'
' 0x0a '
And perhaps a little more straightforwardly:
>>> f'{format(data, "#04x"):^14}'
' 0x0a '
This is a bit ugly but works fine:
'{:^14}'.format('{:#04x}'.format(data))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With