how to get character hex number?

Peter Otten __peter__ at web.de
Sat Sep 1 02:37:00 EDT 2012


Tim Chase wrote:

> On 08/31/12 22:41, contro opinion wrote:
>>>>>>> u"english".encode("utf-8")
>>>> 'english'
>>>>>>> u"english".encode("ascii")
>>>> 'english'
>>>>
>>>> how can i get 656e676c697368 in encode method?
>>>
>>> At least in 2.x, you can do:
>>>
>>>  >>> u"english".encode("hex")
>>>  '656e676c697368'
>>
>> how about in python3.0?
> 
> Well, in 3.1.3 at least, using the u"..." notation dies on me with
> an invalid syntax.  However, as Ian suggests, you can do
> 
>   my_str = "english"
>   "".join("%02x" % c for c in my_str.encode("ascii"))
> 
> or whatever other encoding you want instead of "ascii".

Another option:

>>> binascii.hexlify("english".encode()).decode()
'656e676c697368'





More information about the Python-list mailing list