我正在尝试使用 struct.pack,以便可以将字符串写入文件中。当我这样做时,我收到以下错误:
File "----", line 166, in main
struct.pack('>256s', *master_header)
struct.error: pack expected 1 items for packing (got 256)
现在,阅读 here我好像用对了。我指定在字符串中获取 256 个字节/字符。
我使用的是3.3.3版本。
最佳答案
For the 's' format character, the count is interpreted as the size of the string, not a repeat count like for the other format characters; for example, '10s' means a single 10-byte string, while '10c' means 10 characters.
因此,>256s
需要一个 256 字节长的字符串。如果 master_header
已经是这样的字符串,只需将其传递给 struct.pack
而不带 *
。
在调用站点使用 *
会导致字符串本身被解包为其组成字符,字符串是可迭代的。因此,struct.pack
接收其 256 个单独字符作为参数,从而导致观察到的错误。
关于python - 将 struct.pack 与字符串一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21726324/