Search code examples
pythonhexstring-formatting

How to format an int as an uppercase hex string with 0x prefix?


I have an integer variable:

>>> a = id("string")

and I want to format a to an uppercase hexadecimal string with the prefix 0x. What's the best way to do this?

These are some incorrect outputs:

>>> f"{a:#x}"
'0x115afcae8'

>>> f"{a:#X}"
'0X115AFCAE8'

>>> f"{a:X}"
'115AFCAE8'

I can get the correct output by just prepending 0x to the last of those:

>>> f"0x{a:X}"
'0x115AFCAE8'

but is this really the cleanest way? It sems odd that I couldn't find a way to do this with just the extremely vast string formatting mini-language.


Solution

  • It really seems to be that

    >>> f"0x{a:X}"
    '0x115AFCAE8'
    

    is the best way to do this, as this cannot be done with just string formatting.