簡體   English   中英

合並Python中用空格分割的字符串

[英]Merging a string splitted by space in 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()

變量'line'就像這樣:

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

我什么都沒得到。

這里有些不對勁...

你想使用join

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

但是,更大的問題是您的status=="0"行永遠不會為真(因為status為int),將其更改為

if status == 0:

我沒有完全理解你想要的輸出。 但是當你寫下這一行時:

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

你正在做的是用空格分割字符串,所以輸出目前是:

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

我假設你想要以下輸出?

'20961000000' ?

如果是這樣,只需在print語句之前添加以下行:

"".join(IEEEAddrRemoveDev)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM