[Tutor] hex output

Alan Gauld alan.gauld at blueyonder.co.uk
Fri Sep 5 00:16:35 EDT 2003


> >>>hex(65)
> '0x41'
> >>>hex(65)[2:]
> '41'
> I want to write it in 4 digits form like this  0041
> and also in upper cases.

Use a format string

print "%04X" & 65

The 04 says 4 digits padded with zeros
The upper case X says use upper case Hex.

Make it a function if you like:

>>> def upperHex(d,p=4): 
...    fmt = "%%0%dX" % p
...    return fmt % d
...
>>> print upperHex(65)
0041
>>> print upperHex(65,6)
000041
>>>

HTH,

Alan G.

Alan g.



More information about the Tutor mailing list