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 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 |
|