pythonpython-3.xf-string

How to do alignment on hex in string formatting


Is there a way to align hexadecimal digits in string formatting? I feel like it has to be quite easy, and I'm just missing the formatting. For example:

ones_comp = 72510
print (f"2. Ones comp: {ones_comp:#0x>12}")

I'd like it to print something like:

2. Ones comp:       0x11b3e

Solution

  • You can do:

    print(f"2. Ones comp: {ones_comp:>12x}")
    

    which outputs:

    2. Ones comp:        11b3e
    

    or use the hex function if you really want the 0x prefix:

    print(f"2. Ones comp: {hex(ones_comp):>12}")
    

    which outputs:

    2. Ones comp:      0x11b3e