Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting unicode string to hexadecimal representation

I want to convert unicode string to its hexadecimal representation. For example, u'\u041a\u0418\u0421\u0410' should be converted to "\xD0\x9A\xD0\x98\xD0\xA1\xD0\x90". I tried the code below (python 2.7):

unicode_username.encode("utf-8").encode("hex")

However, I get a string:

'd09ad098d0a1d090'

Any suggestions how I can get \xD0\x9A\xD0\x98\xD0\xA1\xD0\x90?

like image 343
Alex Vyushkov Avatar asked Jan 02 '17 01:01

Alex Vyushkov


1 Answers

When you do string.encode('utf-8'), it changes to hex notation.

But if you print it, you will get original unicode string.

If you want the hex notation you can get it like this with repr() function:

>>> print u'\u041a\u0418\u0421\u0410'.encode('utf-8')
КИСА
>>> print repr(u'\u041a\u0418\u0421\u0410'.encode('utf-8'))
'\xd0\x9a\xd0\x98\xd0\xa1\xd0\x90'
like image 145
Mohammad Yusuf Avatar answered Sep 25 '22 16:09

Mohammad Yusuf