提问人:philipcj 提问时间:9/25/2023 最后编辑:Goku - stands with Palestinephilipcj 更新时间:10/10/2023 访问量:50
在 python 中将 bytes 对象类型的 '\\' 更改为 '\'
Change '\\' to '\' in bytes object type in python
问:
我对 Python 中字节对象类型的用法感到困惑。我正在读取一个 Txt 文件,该文件每行包含 4 个字节的十六进制值。例如,我的一行由十六进制值组成。我想将此值操作为 .81c50400
\x81\xc5\x04\x00
但是,对于字节对象类型,我得到的值为 .我在下面提供了我的实验的细节。\\x81\\xc5\\x04\\x00
with open(file_path, 'r') as file:
words = file.readlines()
word_count = len(word)
for i in range(word_count):
byte_to_txr = r'\x' + str(words[i])
print(bytes(byte_to_send, encoding = 'utf-8'))
结果打印为:
\\x81
\\xc5
\\x04
\\x00
我在这里犯了什么错误?
因为它应该打印\x81\xc5 ...
答:
0赞
Goku - stands with Palestine
9/25/2023
#1
您可以通过以下方式获得所需的值:
import codecs
data = codecs.escape_decode('\\x81\\xc5\\x04\\x00')
print(data)
#output
(b'\x81\xc5\x04\x00', 16)
print(data[0])
#output
b'\x81\xc5\x04\x00'
或
d,y = codecs.escape_decode('\\x81\\xc5\\x04\\x00')
print(d)
#output
b'\x81\xc5\x04\x00'
评论
0赞
philipcj
9/27/2023
非常感谢您的解释。它为我的目的而工作。实际上,我有数字硬件,我正在尝试以十六进制向硬件发送一些数据包。我希望它是 \x81。但是,通过编码,它被转换为 \\x81,硬件将其解释为其他东西。我的问题是 \x81 和 \\x81 之间有真正的区别吗?有没有更好的编码方法?
评论