-1

I have a string like "0013A200305EFF96". I want to change it to be in form "\x00\x13\xA2\x00\x30\x5E\xFF\x96". The special character is "\x". How can I do this in a time efficient way?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137

3 Answers3

6

Python2

>>> "0013A200305EFF96".decode("hex")
'\x00\x13\xa2\x000^\xff\x96'

Python3

>>> bytes.fromhex("0013A200305EFF96")
b'\x00\x13\xa2\x000^\xff\x96'
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

gnibbler's answer is probably what you are really looking for; but for completeness, here is how you can insert any sequence:

>>> '\\x'.join(a[i:i+2] for i in xrange(0, len(a), 2))
Jakub M.
  • 32,471
  • 48
  • 110
  • 179
  • can I change the results in form of hex value if I want namely results will be '\x00\x13\xA2\x00\x30\x5E\xFF\x96' – user2401013 May 20 '13 at 08:51
1

If you mean literal \x:

import re
s= "0013A200305EFF96"
s=re.sub("(..)", r"\x\1",s)
print s

Output

\x00\x13\xA2\x00\x30\x5E\xFF\x96
perreal
  • 94,503
  • 21
  • 155
  • 181
  • Can I ask one question, If I have "\x12" as a string, how can I convert it to be hex value, its type, and value is '\x12' ? – user2401013 May 20 '13 at 08:58