ord() 预期长度为 1 的字符串,但找到了 int

ord() expected string of length 1, but int found

我从网络收到一个字节数组缓冲区,其中包含许多字段。当我想打印缓冲区时,出现以下错误:

(:ord() expected string of length 1, int found

 print(" ".join("{:02X}".format(ord(c)) for c in buf))

我该如何解决这个问题?

Python bytearraybytes 对象在迭代或索引时产生整数,而不是字符。删除 ord() 调用:

print(" ".join("{:02X}".format(c) for c in buf))

来自Bytes documentation:

While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that 0 <= x < 256 (attempts to violate this restriction will trigger ValueError. This is done deliberately to emphasise that while many binary formats include ASCII based elements and can be usefully manipulated with some text-oriented algorithms, this is not generally the case for arbitrary binary data (blindly applying text processing algorithms to binary data formats that are not ASCII compatible will usually lead to data corruption).

进一步:

Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, b[0] will be an integer, while b[0:1] will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)

我不会在 format() function 可以的地方使用 str.format();没有更大的字符串可以将十六进制数字插入:

print(" ".join([format(c, "02X") for c in buf]))

对于 str.join() 调用,使用列表理解稍微快一些,因为 str.join() 调用必须将可迭代对象转换为列表 anyway;它需要进行双重扫描来构建输出。