Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading