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

标签 python string python-2.7 struct printing

所以我有字符串john。我把它打包成一个结构。当我打开它时,如何打印 john?目前它只打印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)

关于python - 如何从结构中打印字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55787847/

相关文章:

c - C中使用getchar存储用户输入的多个字符

c++ - 标识符 "string"未定义?

python 从一个列表创建多个列表

python - 我们可以向 super() 传递什么参数?

python - 实现 group_by_owners 字典

jquery - 检索字典值 jinja

python - 为字符串定义动态函数

python - 如果超过限制则重置 cumsum (python)

c# - 在字符串 : "Input string was not in a correct format" 中使用括号时

Python 3 : Loops, 列表理解和映射比 Python 2 慢?