Getting hex value of a character

Aaron K. Johnson akjmicro at yahoo.com
Thu Dec 12 13:06:58 EST 2002


In message <mailman.1039714767.21019.python-list at python.org>, "Harvey Thomas"
wrote:
> 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'
> >>>

I'm laughing at all the solutions in this thread,some using map(), some using
lib functions like binascii.hexlify(), all great and correct, all different.
I'm laughing because Perl gets the reputaion for "there's more the one way to
do it", and Python for "There's one way to do it", which is, as we now see, a
crock of shit!

Best,
Aaron.




More information about the Python-list mailing list