How To Remove '\x' From A Hex String In Python?
I'm reading a wav audio file in Python using wave module. The readframe() function in this library returns frames as hex string. I want to remove \x of this string, but translate()
Solution 1:
Indeed, you don't have backslashes in your string. So, that's why you can't remove them.
If you try to play with each hex character from this string (using ord()
and len()
functions - you'll see their real values. Besides, the length of your string is just 4, not 16.
You can play with several solutions to achieve your result: 'hex' encode:
'\xff\x1f\x00\xe8'.encode('hex')
'ff1f00e8'
Or use repr()
function:
repr('\xff\x1f\x00\xe8').translate(None,r'\\x')
Solution 2:
One way to do what you want is:
>>> s = '\xff\x1f\x00\xe8'
>>> ''.join('%02x' % ord(c) for c in s)
'ff1f00e8'
The reason why translate
is not working is that what you are seeing is not the string itself, but its representation. In other words, \x
is not contained in the string:
>>> '\\x' in '\xff\x1f\x00\xe8'
False
\xff
, \x1f
, \x00
and \xe8
are the hexadecimal representation of for characters (in fact, len(s) == 4
, not 24
).
Solution 3:
Use the encode method:
>>> s = '\xff\x1f\x00\xe8'
>>> print s.encode("hex")
'ff1f00e8'
Solution 4:
As this is a hexadecimal representation, encode with hex
>>> '\xff\x1f\x00\xe8'.encode('hex')
'ff1f00e8'
Post a Comment for "How To Remove '\x' From A Hex String In Python?"