所以我有字符串john
。我将其打包到一个结构中。打开包装后,如何打印john
?当前仅打印j
。如果我将字符串更改为Sammy
或其他长度不同的名称,是否也一样?我有2个打包和解压缩该结构的函数。我不必担心first_name
的长度。该功能可以帮我实现。
结构基本上是
1
)john
)我的代码
from struct import *
def make_struct(user_id, first_name):
return pack("is", user_id, first_name)
def deconstruct_struct(structure):
return unpack("is", structure)
packed = make_struct(1, "john")
unpacked = deconstruct_struct(packed)
print(unpacked[1])
当前输出为:
j
答案 0 :(得分:3)
您需要将字符串的长度添加到格式字符串中:
packed = pack("i4s", 1, "john")
unpacked = unpack("i4s", packed)
print(unpacked[1])
>> john
如果您需要一个可变长度的字符串-> packing and unpacking variable length array/string using the struct module in python
编辑:
您的解决方案可以这样扩展:
from struct import *
def make_struct(user_id, first_name):
first_name_length = len(first_name)
fmt = "ii{}s".format(first_name_length) #generate format string with length of first_name
return pack(fmt, user_id, first_name_length, first_name) #add the length to the pack
def deconstruct_struct(structure):
user_id, first_name_length = unpack("ii", structure[:8]) #extract only userid and length from the pack
fmt = "ii{}s".format(first_name_length) #generate the format string like above
#return unpack(fmt, structure) #this would return a (user_id, length of first name, first_name) tuple
return (user_id, unpack(fmt, structure)[2]) #this way, we return only the (user_id, first_name) tuple
packed = make_struct(1, "john")
unpacked = deconstruct_struct(packed)