Splitting a String Python within a list
Question: I have a list such as

    
    
    a=['john(is,great),paul,school','robert,jack,john']
    

then I am building an empty list to append the split

    
    
    b=[]
    

then I do this

    
    
    for i in a:
        b.append(i.split(','))
    

but list be is appearing like this

    
    
    [['john(is', 'great)', 'paul', 'school'], ['robert', 'jack', 'john']]
    

Its doing this because its splitting at the comma but is there another way to
split this so this `john(is', 'great)` appears as one string like
`john(is,great)`


Answer: You can use `list.extend()` to add elements individually:

    
    
    for i in a:
        b.extend(i.split(','))
    

To split text on commas _not inside parenthesis_ you could use the following
regular expression:

    
    
    re.split(r',(?=[^()]*(?:\(|$))', i)
    

This splits on a comma only if it is not followed by text containing any
parentheses (opening or closing) until the next opening parenthesis. This
expression falls down when you have nested parenthesis, but works for your
simple case:

    
    
    >>> import re
    >>> i = 'john(is,great),paul,school'
    >>> re.split(r',+(?=[^()]*(?:\(|$))', i)
    ['john(is,great)', 'paul', 'school']
    

For more complex splits, use a full-blown parser.

