Grouping ips from list in python
Question: I have a text file containing 100s of comma separated IPs with just spaces
between them.

I need to take them 10 at a time and put them in another block of code. So,
for IPs:

`1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4, ... 123.123.123.123, 124.124.124.124,
125.125.125.125`

I would need:

    
    
    codethings [1.1.1.1, 2.2.2.2, ... 10.10.10.10] code code code
    codethings [11.11.11.11, 12.12.12.12, ... 20.20.20.20] code code code
    codethings [21.21.21.21, 22.22.22.22, ... 30.30.30.30] code code code
    
    etc
    

I'm pretty sure I could do it with RegEx but I can't help but think there are
simpler ways to do it.

Any and all help appreciated. Thank you!


Answer: Split on comma, strip excessive whitespace from each element:

    
    
    txt = '''1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4, 
        123.123.123.123, 124.124.124.124, 125.125.125.125'''
    
    ip_list = map(str.strip, txt.split(','))
    

As for pagination, see answers for: [Paging python lists in slices of 4
items](http://stackoverflow.com/questions/3950079/paging-python-lists-in-
slices-of-4-items) OR [Is this how you paginate, or is there a better
algorithm?](http://stackoverflow.com/questions/3744451/is-this-how-you-
paginate-or-is-there-a-better-algorithm)

I would also advise (just to be sure) to filter out invalid IP adresses, for
example using a generator and `socket` module:

    
    
    from __future__ import print_function
    import sys
    import socket
    
    txt = '''1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4, 
        123.123.123.123, 124.124.124, 555.125.125.125,'''
    
    def iter_ips(txt):
        for address in txt.split(','):
            address = address.strip()
            try:
                _ = socket.inet_aton(address)
                yield address
            except socket.error as err:
                print("invalid IP:", repr(address), file=sys.stderr)
    
    print(list(iter_ips(txt)))
    

