在Python中合并按空格分割的字符串

2024-10-01 19:24:31 发布

您现在位置: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

我什么也得不到。你知道吗

有点不对劲。。。你知道吗


Tags: 代码inselfforifresponsestatusline
2条回答

我不完全理解你想要的结果。但是当你写这句话的时候:

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

您所做的是将字符串按空格拆分,因此输出当前为:

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

我假设您想要以下输出?你知道吗

'20961000000' ?

如果是这样,只需在打印语句前添加以下行:

"".join(IEEEAddrRemoveDev)

要使用join

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

但是,更大的问题是,您的status=="0"行从来都不是真的(因为status是int),请将它改为

if status == 0:

相关问题 更多 >

    热门问题