Using re.findall is probably a more understandable / flexible method:
>>> s = 'This is "an example text" containing spaces.' >>> ''.join(re.findall(r'(?:".*?")|(?:\S+)', s)) 'Thisis"an example text"containingspaces.'
You can (ab) use csv.reader :
>>> import csv >>> ''.join(next(csv.reader([s.replace('"', '"""')], delimiter=' '))) 'Thisis"an example text"containingspaces.'
Or using re.split :
>>> ''.join(filter(None, re.split(r'(?:\s*(".*?")\s*)|[ ]', s))) 'Thisis"an example text"containingspaces.'
source share