python中struct.unpack的用法

系统 8196 0

python中struct.unpack的用法

4/25/2009 12:18:21 PM

Python中按一定的格式取出某字符串中的子字符串,使用struck.unpack是非常高效的。      
1. 设置fomat格式,如下:        

#
取前5个字符, 跳过4个字符华, 再取3个字符
format = '5s 4x 3s'

            

2. 使用struck.unpack获取子字符串      

 import struct
 print struct.unpack(format, 'Test astring')
#('Test', 'ing')

                


来个简单的例子吧,有一个字符串'He is not very happy',处理一下,把中间的not去掉,然后再输出。      

 import struct
 theString = He is not very happy '
 format = '2s 1x 2s 5x 4s 1x 5s '
 print ' '.join(struct.unpack(format, theString))

 

输出结果:      
He is very happy

利用unpack(),读入一个bin文件,rawstring是一个str型的字串:

rawfile = open("lcd.raw","rb")      
rawstring = rawfile.read()


rawdata = struct.unpack(len(rawstring)*'B',rawstring)

在此处将rawstring转成Byte型数据得到一个rawdata的元组进行处理。


Format C Type Python Notes





 x  pad byteno value
 c    char  string of length 1
 b    signed char  integer
 B    unsigned char  integer
 h    short  integer
 H    unsigned short  integer
 i    int  integer
 I    unsigned int  long
 l    long  integer
 L    unsigned long  long
 q    long long  long(1)
 Q    unsigned long long  long(1)
 f    float  float
 d    double  float
 s    char[]  string
 p    char[]  string
 P    void *  integer



更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论