【问题标题】:How do I convert a bytes object to a string in python?如何在 python 中将字节对象转换为字符串?
【发布时间】:2023-01-13 01:35:10
【问题描述】:

我使用 python netdiscover 工具获取哪些设备连接到我的本地网络,我想将它们的 IP 地址写入文本文件。为此,我想从以下列表中取出 IP 地址,该列表是 netdiscover 的产物:

lst = [{'ip': b'192.168.1.1', 'mac': b'40:35:c1:8e:7e:78'},
       {'ip': b'192.168.1.108', 'mac': b'44:a0:50:56:22:99'},
       {'ip': b'192.168.1.101', 'mac': b'ff:5b:4b:46:70:67'},
       {'ip': b'192.168.1.100', 'mac': b'6a:ef:3b:58:8f:f0'},
       {'ip': b'192.168.1.102', 'mac': b'46:72:b0:ef:3c:a8'}, 
       {'ip': b'192.168.1.104', 'mac': b'58:c2:f5:b1:65:42'}]

IP 地址是bytes 对象。为了将它们转换为字符串以便我可以将它们写入文件,我使用了以下代码:

for i in lst:
    f=i.get("ip")
    f1=str(f)
    f2=f1.partition("b")
    print(f2[2])

这段代码给了我我想要的东西,但对我来说似乎很荒谬。有没有更优雅的方法从列表中取出 IP 地址?

【问题讨论】:

标签: python list dictionary


【解决方案1】:

通过简单的列表理解和 bytes.decode 功能:

ips = [d['ip'].decode() for d in lst]
print(ips)

['192.168.1.1', '192.168.1.108', '192.168.1.101', '192.168.1.100', '192.168.1.102', '192.168.1.104']

【讨论】:

  • 再次,请尝试了解 OP 实际询问的内容,并在存在时将其引导至副本,而不是添加答案
猜你喜欢
  • 2018-12-08
  • 1970-01-01
  • 1970-01-01
  • 2018-05-24
  • 2013-10-24
  • 1970-01-01
  • 2021-05-14
  • 1970-01-01
  • 2021-02-23
相关资源
最近更新 更多