python中struct.unpack的用法
4/25/2009 12:18:21 PM
Python中按一定的格式取出某字符串中的子字符串,使用struck.unpack是非常高效的。
# 取前5个字符, 跳过4个字符华, 再取3个字符 format = '5s 4x 3s'
2. 使用struck.unpack获取子字符串
import struct print struct.unpack(format, 'Test astring') #('Test', 'ing')
import struct theString = He is not very happy ' format = '2s 1x 2s 5x 4s 1x 5s ' print ' '.join(struct.unpack(format, theString))
输出结果:
利用unpack(),读入一个bin文件,rawstring是一个str型的字串: rawfile = open("lcd.raw","rb")
|
在此处将rawstring转成Byte型数据得到一个rawdata的元组进行处理。
Format C Type Python Notes
x | pad byte | no 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 |
本文为张军原创文章,转载无需和我联系,但请注明来自张军的军军小站,个人博客http://www.zhangjunbk.com