Python: Slicing a String based on Indicies and character
Question: I am essentially making a log file parsing program in Python. The issues I am
having is when I am trying to extract out a variable length thing, such as an
IP address.

    
    
    FILE = importFile.readlines()    
    holderString = ''
    cleanUp = []
    
    for line in FILE:
            holderString = line[51:63]
            if holderString not in cleanUp:
                cleanUp.append(holderString)
    

This block of code runs after I already parsed through the log file and have
extracted the lines that contain the keyword I am using. What I really want is
to be able to start at a specific indices, in this case column 51, as where an
IP address starts is predictable. Where it ends though, is the problem. Here
is an example line:

    
    
    [02] Mon 01Jan15 00:00:00 - (1234567) Connected to 192.168.1.1 (local address 10.10.10.10, port 80)
    

The Index, Date, Time, dash, session ID and "Connected to" never change in
length nor their position, but the connecting IP address does change and thus
changes length (example: 19.18.1.1 (length of 9) or 192.168.100.100 (length of
15)).

How would I go about starting at a specific indices and end on a specific
character?


Answer: Slice the string from index 51 till the end, split it by spaces and use the
first element.

    
    
    >>> line = "[02] Mon 01Jan15 00:00:00 - (1234567) Connected to 192.168.1.1 (local address 10.10.10.10, port 80)"
    >>> line[51:].split()[0]
    '192.168.1.1'
    

You can also do it without the slicing part by splitting the whole line at
spaces and taking the 9th splitted element as your ip address:

    
    
    >>> line = "[02] Mon 01Jan15 00:00:00 - (1234567) Connected to 192.168.1.1 (local address 10.10.10.10, port 80)"
    >>> line.split()[8]
    '192.168.1.1'
    

An alternative way is to search for the ip address in your line with an regex:

    
    
    >>> import re
    >>> line = "[02] Mon 01Jan15 00:00:00 - (1234567) Connected to 192.168.1.1 (local address 10.10.10.10, port 80)"
    >>> re.search(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", line).group(0)
    '192.168.1.1'
    

