Quote aware split

John Machin sjmachin at lexicon.net
Wed May 16 07:57:51 EDT 2007


On May 16, 10:50 am, "Ondrej Baudys" <obau... at gmail.com> wrote:

>     # last slice will be of the form chars[last:] which we couldnt do above

Who are "we"? Here's another version with the "couldn't do" problem
fixed and a few minor enhancements:

def qsplit2(chars, sep=",", quote="'"):
    """ Quote aware split """
    assert sep != quote
    can_split = True
    splitpoints = [-1] # ie. separator char found before first
letter ;)
    for index, c in enumerate(chars):
        if c == quote:
            can_split = not can_split
        elif c == sep and can_split:
            splitpoints.append(index)
    if not can_split:
        raise ValueError("Unterminated quote")
    splitpoints.append(len(chars))
    # slice chars by splitpoints *omitting the separator*
    slices = [chars[splitpoints[i]+1:splitpoints[i+1]]
                                for i in range(len(splitpoints)-1)]
    return slices

Cheers,
John




More information about the Python-list mailing list