Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - using format/f string to output hex with 0 padding AND center

Tags:

python

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
like image 285
Ack Avatar asked Oct 16 '18 20:10

Ack


2 Answers

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     '
like image 115
dawg Avatar answered Oct 22 '22 15:10

dawg


This is a bit ugly but works fine:

'{:^14}'.format('{:#04x}'.format(data))
like image 33
ale-cci Avatar answered Oct 22 '22 15:10

ale-cci