2013-03-11 37 views
3

分裂我有這樣的碼的一部分的字符串:合併通過空間在Python

for line in response.body.split("\n"): 
    if line != "": 
     opg = int(line.split(" ")[2]) 
     opc = int(line.split(" ")[3]) 
     status = int(line.split(" ")[5]) 
     if command == 'IDENTIFY': 
      if opg==opcodegroupr and opc==opcoder: 
       if status=="0": 
      IEEEAddrRemoteDev = line.split(" ")[6:14] 
     ret['success'] = "IDENTIFY: The value is %s " % (IEEEAddrRemoteDev) 
     self.write(tornado.escape.json_encode(ret)) 
     self.finish() 

變量「線」是這樣的,例如:

1363011361 2459546910990453036 157 0 17 0 209 61 0 0 0 0 0 0 0 0 0 0 0 0 0 201 

我將例如採取字段從6到14並且「合併」彼此以像整個字符串那樣打印IEEEAddrRemoteDev。

這是

IEEEAddrRemoteDev = line.split(" ")[6:14] 

正確的方法是什麼?如果我寫

print IEEEAddrRemoteDev 

我沒有得到任何東西。

有問題的話...

+0

我不知道爲什麼你沒有得到任何東西,但加盟的字符串是這樣的:'「」。 join(line.split(「」)[6:14])' – hughdbrown 2013-03-11 14:31:33

+2

你永遠不會得到任何輸出的原因是,如果status ==「0」:'永遠不是真的,因爲你將它轉換爲int。看到我的回答 – 2013-03-11 14:40:23

回答

6

你想用join

ret['success'] = "IDENTIFY: The value is %s " % (" ".join(IEEEAddrRemoteDev)) 

然而,更大的問題是,你的status=="0"線是不正確的(因爲status是一個int),將其更改到

if status == 0: 
+0

我懷疑這會解決問題,因爲'如果我寫打印IEEEAddrRemoteDev我沒有獲得任何東西'。我認爲OP在輸入的某個地方有一個空的「行」,這就是拋棄算法 – inspectorG4dget 2013-03-11 14:32:51

+1

@ inspectorG4dget,這有點奇怪,但是在這種情況下,只有空行應該有一個空輸出。 – 2013-03-11 14:34:24

+0

@ inspectorG4dget:排序 - 問題是他的'if status =='0''行,這意味着他從來沒有從print語句中得到任何輸出,因爲條件從未滿足(status是一個'int') 。 – 2013-03-11 14:41:11

0

我沒有完全理解你的期望輸出。但是,當你寫的一行:

IEEEAddrRemoteDev = line.split(" ")[6:14] 

你在做什麼是由分裂的空白串,所以輸出是目前:

['209', '61', '0', '0', '0', '0', '0'] 

我想,你希望下面的輸出?

'20961000000' ? 

如果是這樣,只是你的打印語句前加上下面一行:

"".join(IEEEAddrRemoveDev)