ord()预期的字符串长度为1,但找到int [英] ord() expected string of length 1, but int found

查看:113
本文介绍了ord()预期的字符串长度为1,但找到int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I receive a byte-array buffer from network, containing many fields. When I want to print the buffer, I get the following error:

(:ord()期望的字符串,长度为1,整数找到

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

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

我该如何解决?

推荐答案

Python bytearray bytes 对象在迭代或建立索引时会产生整数,而不是字符.删除 ord()调用:

Python bytearray and bytes objects yield integers when iterating or indexing, not characters. Remove the ord() call:

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

来自 字节 文档:

虽然字节文字和表示是基于ASCII文本的,但字节对象实际上的行为就像不可变的整数序列,序列中的每个值都受到限制,以使 0< = x<256 (尝试违反此限制将触发 ValueError .这样做是为了强调,尽管许多二进制格式都包含基于ASCII的元素,并且可以使用某些面向文本的算法来进行有效地操作,但这任意二进制数据通常不是这种情况(将文本处理算法盲目地应用于不兼容ASCII的二进制数据格式通常会导致数据损坏).

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).

并进一步:

因为字节对象是整数序列(类似于元组),所以对于字节对象 b b [0] 将是整数,而b [0:1] 将是一个长度为1的字节对象.(这与文本字符串形成对比,在文本字符串中,索引和切片都会产生一个长度为1的字符串)

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)

我不使用 str.format(),其中

I'd not use str.format() where a format() function will do; there is no larger string to interpolate the hex digits into:

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

对于 str.join()调用,由于 str.join()调用必须将可迭代对象转换为列表,因此使用列表理解要快一些.无论如何;它需要进行两次扫描以构建输出.

For str.join() calls, using list comprehension is marginally faster as the str.join() call has to convert the iterable to a list anyway; it needs to do a double scan to build the output.

这篇关于ord()预期的字符串长度为1,但找到int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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