tags:

views:

227

answers:

2

Exact duplicate: http://stackoverflow.com/questions/79968/split-a-string-by-spaces-in-python


I want to take in a string and return a list, dictionary or tuple of values as separated by spaces. However, I want to not match spaces that are somehow between quote marks, i.e.

apple orange "banana tree" green

Should come back as three items, "banana tree" being one whole item.

If possible it should also allow for the escaping of quote marks.

+1  A: 

This problem sounds a lot like parsing tag input, you could take a look at django-tagging utils.py implementation which solves this kind of problem

Jonas
A: 
def splitstring(string):
    """
    >>> string = 'apple orange "banana tree" green'
    >>> splitstring(string)
    ['apple', 'orange', 'green', '"banana tree"']
    """
    import re
    p = re.compile(r'"[\w ]+"')
    quoted_item = p.search(string).group()
    newstring = p.sub('', string)
    return newstring.split() + [quoted_item]
Aaron
Fails for some input; try splitstring('apple "foo bar" baz "qux"')
Charles Duffy
This not only reorders the items, it also only works for one quoted item.
Jared Forsyth