2016-05-15 59 views
1

我需要從這個字符串中提取信息,內幕信息「隨機」(是字節,但我解碼吧):獲取放在一個字符串

\ X00 \ X00 \ X00播出的「updatedirection 126.0」

我需要看看它是否包含廣播,更新方向,並看看最後的數字是什麼。我的第一個解決方案是:

data = data.split('!') 
data = data[1] 

但在該位置的符號似乎隨機變化,根本沒有明顯的模式。然後我嘗試了:

data = data[12:] 

但是字符串的長度一直在改變,所以沒有工作。

我這樣做是爲了在學校裏使用BYOB(基於Scratch,一種簡單的語言教青少年如何編程)的計算機科學項目,以及在它們之間發送數據以製作局域網多人遊戲的套接字。這實際上是唯一不起作用的東西。

希望有人能給我一個解決方案來找到這些數據。

+1

使用正則表達式 –

+0

'import re'' print re.findall('!broadcast「updatedirection [\ d。] +」',INPUT)'' – YOU

回答

1

要檢查是否字符串包含一個字:

if word in string: 

然後我會用rfind()找到其中最後空間,提取該空間後的文本,檢查它是否是一個數字。

可以測試在一個語句兩個詞:

str = "test it here" 

if "test" in str and "here" in str: 
    print("they are") 
0

試試這個,

import re 

s = '\x00\x00\x00!broadcast "updatedirection 126.0"' 

# if 'broadcast' in s and 'updatedirection' in s: 
if all([item in s for item in ['broadcast', 'updatedirection']]): 
    result = re.findall('[-+]?\d*\.\d+|\d+', s) # extract all numbers from a string 

    print(result[-1]) # the last number 
    # Output 
    126.0 

參考re.findall

2

你可以用錘子

import re 

s = '\x00\x00\x00!broadcast "updatedirection 126.0"' 
pat = re.compile(r'(?:\x00){3}\Wbroadcast "updatedirection ([\d.]+)"') 
m = pat.match(s) 
if m: 
    print(m.group(1)) # '126.0' 

檢查不同的情況下打它,

s = '\x00\x00\x00#broadcast "updatedirection 126.0"' 
pat.match(s).group(1) # '126.0' 

s = '\x00\x00\x00!foo "bar 126.0"' 
pat.match(s) # None 

你可以使其更加堅固,通過改變對正則表達式的空字節的第一部分類似於給它的範圍是(?:\x00){m,n}或類似的東西。