-2
ip = a list of ips
ipf = list(filter(lambda x: x if not x.startswith(str(range(257,311))) else None, ip))

Is is possible to do something like this? I tested it and it doesn't work. I'd like to delete all ips from "ip" list that start with 256. 257. 258. ecc... to 310.

CatchJoul
  • 87
  • 2
  • 8

1 Answers1

3

No, str.startswith() doesn't take a range.

You'd have to parse out the first part and test it as an integer; filtering is also easier done with a list comprehension:

[ip for ip in ip_addresses if 257 <= int(ip.partition('.')[0]) <= 310]

The alternative would be to use the ipaddress library; it'll reject any invalid address with a ipaddress.AddressValueError exception, and since addresses that start with anything over 255 are invalid, you can easily co-opt that to filter out your invalid addresses:

import ipaddress

def valid_ip(ip):
    try:
        ipaddress.IPv4Address(ip)
    except ipaddress.AddressValueError:
        return False
    else:
        return True

[ip for ip in ip_addresses if valid_ip(ip)]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343