Python中struct.pack的一个疑问

编程入门 行业动态 更新时间:2024-10-27 11:19:56
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).

更多推荐

本文发布于:2023-07-14 23:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1108327.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:疑问   Python   struct   pack

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!