[Tutor] Converting ascii string to hex?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Aug 13 02:32:41 EDT 2003



> Here's an even more kludy (but more working version:
>
> >>> def asctohex(string_in):
> ...     a=""
> ...     for x in string_in:
> ...         a = a + ("0"+((hex(ord(x)))[2:]))[-2:]
> ...     return(a)
> ...
> >>> print asctohex("a 1")
> 612031
> >>> print asctohex(chr(10))
> 0a
> >>>
>
> There *is* a cleaner way, isn't there?  Is there nothing akin to what I
> imagine would be simply
>
>  hex(s)
>
> where "s" is a string?


Hi Terry,

Yes: check the 'binascii' module:

    http://www.python.org/doc/lib/module-binascii.html#l2h-3835

binascii.hexlify() should do the trick:

###
>>> binascii.hexlify('hello world')
'68656c6c6f20776f726c64'
###


binascii.unhexlify('486f706520746869732068656c707321')




More information about the Tutor mailing list