Alex Vyushkov
Alex Vyushkov

Reputation: 680

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?

Upvotes: 8

Views: 35711

Answers (3)

MST
MST

Reputation: 721

Another solution:

result = '\\x' + 'your input string'.encode('utf-8').hex(' ').replace(' ', '\\x')
print(result)

Result:

\x79\x6f\x75\x72\x20\x69\x6e\x70\x75\x74\x20\x73\x74\x72\x69\x6e\x67

Upvotes: 0

Mohammad Yusuf
Mohammad Yusuf

Reputation: 17074

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'

Upvotes: 10

Joniale
Joniale

Reputation: 595

you can also try:

print "hex_signature :  ",'\\X'.join(x.encode("hex") for x in signature)

The join function is used with the separator '\X' so that for each byte to hex conversion the \X is inserted. The join function is done for each byte of the variable signature in a loop. Everything is joined/concatenated and printed.

Upvotes: 1

Related Questions