Getting hex value of a character

Harvey Thomas hst at empolis.co.uk
Thu Dec 12 12:36:28 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.
> 
> --
> 
> Dennis Reinhardt
> 
> http://www.dair.com
> 

This works:

>>> ''.join([hex(ord(x))[2:] for x in "AB"])
'4142'
>>> ''.join([hex(ord(x))[2:] for x in "ABC"])
'414243'
>>>

Harvey

_____________________________________________________________________
This message has been checked for all known viruses by the MessageLabs Virus Scanning Service.




More information about the Python-list mailing list