Slicing a String after certain key words are mentioned into a list
Question: I am new to python and I am stuck with a problem. What I'm trying to do that I
have a string containing a conversation between two people :

    
    
    str = "  dylankid: *random words* senpai: *random words* dylankid: *random words* senpai: *random words*"
    

I want to create 2 lists from the string using dylankid and senpai as names :

    
    
    dylankid = [ ]
    senpai = [ ]
    

and here is where I am struggling, inside list dylankid I want to place all
the words that come after 'dylankid' in the string but before the next
'dylankid' or 'senpai' same goes for senpai list so it would look something
like this

    
    
    dylankid = ["random words", "random words", "random words"]
    senpai = ["random words", "random words", "random words"]    
    

dylankid containing all the messages from dylankid and vice versa.

I have looked into slicing it and using `split()` and `re.compile()`, but I
can't figure out a way to specify were to start slicing and where to stop.

Hopefully it was clear enough, any help would be appreciated :)


Answer: Following code will create a dict where keys are persons and values are list
of messages:

    
    
    from collections import defaultdict
    import re
    
    PATTERN = '''
        \s*                         # Any amount of space
        (dylankid|senpai)           # Capture person
        :\s                         # Colon and single space
        (.*?)                       # Capture everything, non-greedy
        (?=\sdylankid:|\ssenpai:|$) # Until we find following person or end of string
    '''
    s = "  dylankid: *random words* senpai: *random words* dylankid: *random words* senpai: *random words*"
    res = defaultdict(list)
    for person, message in re.findall(PATTERN, s, re.VERBOSE):
        res[person].append(message)
    
    print res['dylankid']
    print res['senpai']
    

It will produce following output:

    
    
    ['*random words*', '*random words*']
    ['*random words*', '*random words*']
    

