0

I have three hex strings:

hex1 = "e0"
hex2 = "aa"
hex3 = "b0"
string = "\\x"+hex1+"\\x"+hex2+"\\x"+hex3

print string

When I concatenate those three strings after appending "\x" to each of them I don't get its character representation.

I get output as \xe0\xaa\xb0

But when I define it in one line

string = "\xe0\xaa\xb0"

and print string I get correct output which is

What is wrong in my previous attempt?

2
  • Remove one extra \ from \\x and try to append. Commented Jan 18, 2016 at 6:00
  • Sorry, there was typo. Please read my comment above. Commented Jan 18, 2016 at 6:03

2 Answers 2

2

Try

lst = [
    chr(int(hex1, 16)),
    chr(int(hex2, 16)),
    chr(int(hex3, 16))
]
s = ''.join(lst)  # '\xe0\xaa\xb0'

Your method won't work because the initial string "\\x" is interpreted as the string "\x" - and as you probably saw, creating the initial string with a single backslash ("\x") is invalid.

Sign up to request clarification or add additional context in comments.

Comments

0

Python comes with a lot of useful libraries, and there is a Python library for what you want, binascii. binascii.unhexlify converts a hex sequence like '010203' into bytes '\x01\x02\x03':

>>> hex1 = "e0"
>>> hex2 = "aa"
>>> hex3 = "b0"
>>> s = hex1+hex2+hex3
>>> import binascii
>>> binascii.unhexlify(s)
'\xe0\xaa\xb0'

There is even a method for what you were originally trying to do:

>>> hex1 = "e0"
>>> hex2 = "aa"
>>> hex3 = "b0"
>>> s= "\\x"+hex1+"\\x"+hex2+"\\x"+hex3
>>> s.decode('string-escape')
'\xe0\xaa\xb0'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.