ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2019-11-08 04:57:26  阅读:313  来源: 互联网

标签:python-2-7 struct printing string python


所以我有字符串约翰.我将其打包到一个结构中.当我打开包装时,如何打印约翰?当前仅打印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-2-7,struct,printing,string,python
来源: https://codeday.me/bug/20191108/2005649.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有