Thavivelball Thavivelball - 2 months ago 8
Python Question

Startswith with a range of number instead an unit

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.

Answer

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)]
Comments