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 273 times
-1
Micha Wiedenmann
- 18,825
- 20
- 87
- 132
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
- 281,034
- 50
- 354
- 495
-
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.
- 30,095
- 43
- 103
- 169
-
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
- 90,214
- 20
- 145
- 172
-
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