Home > database >  How do I convert a bytes object to a string in python?
How do I convert a bytes object to a string in python?

Time:01-13

I used python netdiscover tool to obtain which devices are connected to my local network, and I want to write their IP addresses into a text file. To do this, I want to take out IP addresses from the following list which is the product of 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'}]

The IP addresses are bytes object. To convert them to a string so that I can write them to a file, I used the following code:

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

This code gave me what I desire, but it seems ridiculous to me. Is there a more elegant way to take out the IP addresses from list?

CodePudding user response:

With simple list comprehension and bytes.decode function:

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']

CodePudding user response:

You can use this .Hope it helpes.. [1]: https://i.stack.imgur.com/ggOQ7.png

  • Related