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?
Asked
Active
Viewed 286 times
-1

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

user2401013
- 1
- 2
3 Answers
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
-
1what is this ^in results – user2401013 May 20 '13 at 08:45
-
You want to escape the printable characters too? – John La Rooy May 20 '13 at 08:46
-
result should be also in form of string – user2401013 May 20 '13 at 08:47
-
So the \ are literal? – John La Rooy May 20 '13 at 08:50
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