17

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
Ack
  • 255
  • 1
  • 3
  • 9
  • 1
    Format the data twice: first by padding and hex formatting, then a second time with centering. I think this will make it easier to understand what is going on anyway. – Willem Van Onsem Oct 16 '18 at 20:15
  • 1
    `'{:^14s}'.format('{:#04x}'.format(data))` – dawg Oct 16 '18 at 20:17
  • 1
    This reminds me of a need I had in a templating function to pass in the width I was padding strings to. Slightly different solution here than there, but it ended up being the (rather sly) `"{{:>{}.2f}}".format(width).format(num)` – Adam Smith Oct 16 '18 at 21:17

2 Answers2

27

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     '
dawg
  • 98,345
  • 23
  • 131
  • 206
  • 1
    "perhaps" abusively ;) – Adam Smith Oct 16 '18 at 21:14
  • 2
    It is debatable whether nested f strings are intended, but this is a example of a good use. – dawg Oct 16 '18 at 21:15
  • @IceflowerS: I just retested all four examples on Python 3.10 and all produce the output described. What do you mean 'this does not work?' – dawg Nov 18 '21 at 12:29
  • MacOS Python 3.10.0 Oct 22, 2021. That string `>>> '{:^14s}'.format(f'{data:#02x}') ` produces `' 0xa '`. Maybe try breaking into constituent parts? What happens with `'{:^14s}'.format("X")` for example? – dawg Nov 18 '21 at 13:00
  • @IceflowerS: Don't know how to comment on something I cannot reproduce. It works on MacOS and Linux with Python 3.8-3.10. – dawg Nov 18 '21 at 13:07
  • the last edit of your post by @hans-ginzel made the output wrong. – Iceflower S Nov 18 '21 at 13:16
  • I rolled it back – dawg Nov 18 '21 at 13:47
4

This is a bit ugly but works fine:

'{:^14}'.format('{:#04x}'.format(data))
ale-cci
  • 153
  • 2
  • 11