python 3.3:struct.pack不接受字符串

2024-06-28 20:12:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用struct.pack将填充字符串写入文件,但对于3.x解释器,这似乎不再有效。我使用它的一个例子:

mystring = anotherString+" sometext here"
output = struct.pack("30s", mystring);

这在早期版本的python中似乎是可以接受的,但是对于3,它会产生一个要求字节对象的错误。这些文档似乎暗示它应该毫无怨言地将任何字符串转换为UTF-8字节对象(我不在乎多字节字符是否被截断):

http://docs.python.org/release/3.1.5/library/struct.html“c、s和p转换代码对bytes对象进行操作,但是用这些代码打包也支持str对象,这些对象使用UTF-8编码。”

我是否误读了这些文档,以及其他人如何使用带字符串的struct.pack?


Tags: 文件对象字符串代码文档字节here解释器
2条回答

我可能是错的,但在这种情况下,.encode('UTF-8')不起作用吗? 例如:

output = struct.pack("30s", mystring.encode('UTF-8'));

我要被纠正。

是的,直到3.1 struct.pack()错误地将字符串隐式编码为UTF-8字节;这在Python 3.2中得到了修复。见issue 10783

结论是,隐式转换是一个坏主意,当开发人员仍有机会这样做时,它被还原:

I prefer to break the API today than having to maintain a broken API for 10 or 20 years :-) And we have a very small user base using Python 3, it's easier to change it now, than in the next release.

这也记录在porting section of the 3.2 What's New guide

struct.pack() now only allows bytes for the s string pack code. Formerly, it would accept text arguments and implicitly encode them to bytes using UTF-8. This was problematic because it made assumptions about the correct encoding and because a variable-length encoding can fail when writing to fixed length segment of a structure.

打包之前需要显式地对字符串进行编码。

相关问题 更多 >