python中struct.unpack的用法

python中struct.unpack的用法  

 

python中struct.unpack的用法
Python中按一定的格式取出某字符串中的子字符串,使用struck.unpack是非常高效的。
1. 设置fomat格式,如下:
python中struct.unpack的用法 - h-zy2008 - h-zy2008的博客# 取前5个字符,跳过4个字符华,再取3个字符
python中struct.unpack的用法 - h-zy2008 - h-zy2008的博客
format = '5s 4x 3s'

2. 使用struck.unpack获取子字符串
python中struct.unpack的用法 - h-zy2008 - h-zy2008的博客import struct
   print
struct.unpack(format, 'Test astring' )
python中struct.unpack的用法 - h-zy2008 - h-zy2008的博客
#('Test', 'ing')

来个简单的例子吧,有一个字符串'He is not very happy',处理一下,把中间的not去掉,然后再输出。
python中struct.unpack的用法 - h-zy2008 - h-zy2008的博客import struct
python中struct.unpack的用法 - h-zy2008 - h-zy2008的博客theString
= 'He is not very happy'

python中struct.unpack的用法 - h-zy2008 - h-zy2008的博客format
= '2s 1x 2s 5x 4s 1x 5s'
python中struct.unpack的用法 - h-zy2008 - h-zy2008的博客
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的元组进行处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值