如何从 Python 中的十六进制字符串中删除“\x"? [英] How to remove '\x' from a hex string in Python?
问题描述
我正在使用 wave
模块在 Python 中读取 wav
音频文件.此库中的 readframe()
函数将帧作为十六进制字符串返回.我想删除这个字符串的 \x
,但是 translate()
函数不能按我想要的那样工作:
我想以任何方式将结果值除以 2,然后再次添加 \x
并生成一个包含这些新值的新 wav
文件.有人有更好的主意吗?
怎么了?
确实,您的字符串中没有反斜杠.所以,这就是您无法删除它们的原因.
如果您尝试使用此字符串中的每个十六进制字符(使用 ord()
和 len()
函数 - 您将看到它们的真实值.此外,您的字符串长度仅为 4,而不是 16.
您可以使用多种解决方案来实现您的结果:十六进制"编码:
'\xff\x1f\x00\xe8'.encode('hex')'ff1f00e8'
或者使用repr()
函数:
repr('\xff\x1f\x00\xe8').translate(None,r'\\x')
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()
function doesn't work as I want:
>>> input = wave.open(r"G:\Workspace\wav\1.wav",'r')
>>> input.readframes (1)
'\xff\x1f\x00\xe8'
>>> '\xff\x1f\x00\xe8'.translate(None,'\\x')
'\xff\x1f\x00\xe8'
>>> '\xff\x1f\x00\xe8'.translate(None,'\x')
ValueError: invalid \x escape
>>> '\xff\x1f\x00\xe8'.translate(None,r'\x')
'\xff\x1f\x00\xe8'
>>>
Any way I want divide the result values by 2 and then add \x
again and generate a new wav
file containing these new values. Does any one have any better idea?
What's wrong?
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')
这篇关于如何从 Python 中的十六进制字符串中删除“\x"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!