2014-05-16 43 views
1

我得到了一個字符串格式的特殊數據包,它有32個字節的頭部,主體包含多個條目之一,每個條目包含90個字節。如何從python的s字符串中刪除前4個字節

我想用python處理這個字符串。我能讀取像襪子讀取第一個32字節的標題,並將其從字符串中取出,並繼續讀取第一個條目的90個字節?

類似:

str.read(32) # => "x01x02..." 
str.read(90) # => "x02x05..." 
+0

切片(S [5:])沒有幫助? – Aadith

+0

你使用的是Python 2.x還是3.x? – Roberto

+0

@Roberto我正在使用python 2.x – mko

回答

4

您可以使用StringIO讀取一個字符串像一個文件

>>> import StringIO 
>>> s = 'Hello, World!' 
>>> sio = StringIO.StringIO(s) 
>>> sio.read(6) 
'Hello,' 
>>> sio.read() 
' World!' 

我也建議你看一看在struct模塊中解析二進制數據幫助

>>> from struct import * 
>>> pack('hhl', 1, 2, 3) 
'\x00\x01\x00\x02\x00\x00\x00\x03' 
>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03') 
(1, 2, 3) 

您可以使用格式字符串定義數據的格式,因此在上例中的'hhl'short (2 bytes), short (2 bytes), int (4 bytes)。它還支持在格式字符串中指定字節順序(字節順序)。

例如,如果你的頭格式爲uint, 4 byte str, uint, uint, ushort, ulong

>>> import struct 
>>> data = ''.join(chr(i) for i in range(128)) * 10 
>>> hdr_fmt = 'I4sIIHL' 
>>> struct.calcsize(hdr_fmt) 
32 
>>> struct.unpack_from(hdr_fmt, data, 0) 
(50462976, '\x04\x05\x06\x07', 185207048, 252579084, 4368, 2242261671028070680) 
4

在蟒蛇2.x中,你可以做簡單:

header = s[:32] 
body = s[32:32+90] 

在蟒蛇3.x的所有字符串都是unicode的,所以我會轉換爲字節組首先:

s = bytearray(s) 
header = s[:32] 
body = s[32:32+90] 
5

將數據包拆分爲32字節的標題和正文:

header = packet[:32] 
body = packet[32:] 

爲了進一步分裂在體內轉化爲一個或多個條目:

entries = [packet[i:i+90] for i in range(0, len(packet), 90)] 
相關問題