gpt4 book ai didi

python - python3 中的 byte 与 str.encode

转载 作者:行者123 更新时间:2023-12-01 01:49:45 24 4
gpt4 key购买 nike

我使用的是python3.5,让

M = '\x09\x00\x00\x00\x01\x89\x02\xdb\xd6\x01\x49\x63\x74'

为什么下面的比较左边部分不等于右边部分?

> M.encode() == b'\x09\x00\x00\x00\x01\x89\x02\xdb\xd6\x01\x49\x63\x74'
$ FALSE

两者的类型都是字节。如何从 M 到达包含上述比较的正确部分的变量?

最佳答案

不是编码专家,但无论您选择哪种编码,如果不正确,它都会解释字符,并且结果将与字节对象不同。

它适用于纯 ascii,但不适用于您的值。

一种方法是根据 ord 提供的字符代码重建 bytes 对象:

M = '\x09\x00\x00\x00\x01\x89\x02\xdb\xd6\x01\x49\x63\x74'
N = b'\x09\x00\x00\x00\x01\x89\x02\xdb\xd6\x01\x49\x63\x74'

M2 = bytes(map(ord,M))

print(N == M2)

产量True:)

关于python - python3 中的 byte 与 str.encode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50856366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com