Getting hex value of a character

P_spam_ at draigBrady.com P_spam_ at draigBrady.com
Thu Dec 12 12:31:13 EST 2002


Dennis Reinhardt wrote:
> I am trying to print the hexadecimal value of a string.  In other words, the
> string "AB" would print as "4142".  I simply cannot get the formatting
> right.  Here is a test case:
> 
>     rawg = "g"
>     print "hex = %02x" % rawg
>     print "hex = %02x" % int(rawg)
>     print "hex = %02x" % string.atoi(rawg)
>     print "hex = %02x" % struct.unpack("c", rawg)
>     print "hex = %02x" % int(struct.unpack("c", rawg))
> 
> None of the print statements I have tried above work.  A common problem to
> many is that int cannot convert the argument given.  The result I am hoping
> for here is "hex = 67".  This must be really simple but I am not getting it
> and have consulted the indexes of 4 Python books.

ord is the missing link

''.join(map(lambda c: "%02X" % ord(c), "AB"))

Pádraig.




More information about the Python-list mailing list