如何从 Python 中的十六进制字符串中删除“\x"? [英] How to remove '\x' from a hex string in Python?

查看:75
本文介绍了如何从 Python 中的十六进制字符串中删除“\x"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 wave 模块在 Python 中读取 wav 音频文件.此库中的 readframe() 函数将帧作为十六进制字符串返回.我想删除这个字符串的 \x,但是 translate() 函数不能按我想要的那样工作:

<预><代码>>>>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: 无效 \x 转义>>>'\xff\x1f\x00\xe8'.translate(None,r'\x')'\xff\x1f\x00\xe8'>>>

我想以任何方式将结果值除以 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆