Python中struct.pack的一个疑问
import struct zzz = "{Type:2}" a = struct.pack("s",zzz.encode("utf-8")) print(a) 为什么输出结果是 b'{' 而不是我要的字符串转成的字节流? 为什么大括号后面都被截掉了? 我用的是Python3.3
最满意答案
的确很奇怪。我试验了10几分钟,你按下面的方法来做就可以正确。 import struct zzz = ("{Type:2}").encode("utf-8") length = len(zzz) a = struct.pack("%ds"%length,zzz) print(a)简单的说s其实只是一个字符,所以前面要加一个数字,比如8s,就可以存贮一个长度为8的字符串。你只写一个s当然只存贮一个。 python帮助的原文如下 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. If a count is not given, it defaults to 1. For packing, the string is truncated or padded with null bytes as appropriate to make it fit. For unpacking, the resulting string always has exactly the specified number of bytes. As a special case, '0s' means a single, empty string (while '0c' means 0 characters).更多推荐
发布评论