我如何从结构中打印字符串?

所以我有字符串约翰.我将其打包到一个结构中.当我打开包装时,如何打印约翰?当前仅打印j.如果我将字符串更改为Sammy或其他长度不同的名称,是否也一样?我有2个打包和解压缩该结构的函数.我不必担心first_name的长度.该功能可以为我做.

结构基本上是

> user_id(在本例中为1)
> first_name(人的名字.此字符串的长度可以不同.在这种情况下为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

解决方法:

您需要将字符串的长度添加到格式字符串中:

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)
上一篇:使用点矩阵打印机进行打印的PHP


下一篇:解决中文乱码( jsp表单提交中文时出现乱码)