Search code examples
pythonhexdigit

Python: converting single digit decimal to hex


Is there any way to get hex (5) output '0x05' instead of '0x5'?

For example i want to convert [255,11,132] to hex string like 'ff0b84' So i can slice it by 2 characters and covert to decimal again. But python doesn't put 0 before b so i can't slice string by 2 characters!


Solution

  • I think you could use format to get '0x05' instead of '0x5':

    In [64]: format(5, '#04x')
    Out[64]: '0x05'
    
    In [65]: format(15, '#04x')
    Out[65]: '0x0f'