简体   繁体   English

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

[英]How do I print a string from a struct?

So I have the string john . 所以我有字符串john I pack it into a struct. 我将它打包成一个结构。 When I unpack it, how can I print john ? 打开包装时,我怎么打印john Currently it only prints j . 目前它只打印j Same thing if I changed the string to Sammy or other names with different lengths? 如果我将字符串更改为Sammy或其他不同长度的名称,同样的事情? I have 2 functions to pack and unpack the struct. 我有2个函数来打包和解压缩struct。 This what I don't need to worry about the lengths of the first_name 's. 这就是我不需要担心first_name的长度。 The function can do it for me. 该功能可以为我做。

The structure is basically 结构基本上是

  • user_id (in this case 1 ) user_id(在这种情况下为1
  • first_name (a person first name. This string can be of different lengths. In this case john ) first_name(一个人的名字。这个字符串可以有不同的长度。在这种情况下john

My Code 我的守则

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])

Current output is: 目前的输出是:

j

You need to add the length of the string to the format string: 您需要将字符串的长度添加到格式字符串:

packed = pack("i4s", 1, "john")
unpacked = unpack("i4s", packed)
print(unpacked[1])
>> john

If you need a string of variable length -> packing and unpacking variable length array/string using the struct module in python 如果你需要一个可变长度的字符串 - > 使用python中的struct模块打包和解包变量长度数组/字符串

EDIT: 编辑:

Your solution can be extended like this: 您的解决方案可以像这样扩展:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM