1

What is the most 'Pythonic' way of translating

'\xff\xab\x12'

into

'ffab12'

I looked for functions that can do it, but they all want to translate to ASCII (so '\x40' to 'a'). I want to have the hexadecimal digits in ASCII.

2
  • Which version of Python are you using? Commented Jun 20, 2016 at 10:04
  • @JonClements 2.7.3 Commented Jun 20, 2016 at 10:05

2 Answers 2

5

There's a module called binascii that contains functions for just this:

>>> import binascii
>>> binascii.hexlify('\xff\xab\x12')
'ffab12'
>>> binascii.unhexlify('ffab12')
'\xff\xab\x12'
Sign up to request clarification or add additional context in comments.

Comments

0
original = '\xff\xab\x12'
result = original.replace('\\x', '')
print result

It's \x because it's escaped. a.replace(b,c) just replaces all occurances of b with c in a.

What you want is not ascii, because ascii translates 0x41 to 'A'. You just want it in hexadecimal base without the \x (or 0x, in some cases)

Edit!!
Sorry, I thought the \x is escaped. So, \x followed by 2 hex digits represents a single char, not 4..

print "\x41"

Will print

A

So what we have to do is to convert each char to hex, then print it like that:

res = ""
for i in original:
   res += hex(ord(i))[2:].zfill(2)
print res

Now let's go over this line:

hex(ord(i))[2:]

ord(c) - returns the numerical value of the char c
hex(i) - returns the hex string value of the int i (e.g if i=65 it will return 0x41.
[2:] - cutting the "0x" prefix out of the hex string.
.zfill(2) - padding with zeroes

So, making that with a list comprehension will be much shorter:

result = "".join([hex(ord(c))[2:].zfill(2) for c in original])
print result

4 Comments

But my original string is not escaped. It is what I said it is: '\xff\xab\x12'.
Oh, so if that's your original string (not escaped) I'll edit my answer :)
And I do want ASCII, because I need to send it as ASCII to a site.
Corrected and added explanation

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.