split a line, respecting double quotes

vbgunz vbgunz at gmail.com
Fri Jul 7 17:44:57 EDT 2006


Jim wrote:
> Is there some easy way to split a line, keeping together double-quoted
> strings?

using the re module I find this to probably be the easiest but in no
way is this gospel :)

import re
rex = re.compile(r'(".*?"|\S)')
sub = 'a b c "d e"'
res = [x for x in re.split(rex, sub) if not x.isspace()][1:-1]
print res # -> ['a', 'b', 'c', '"d e"']

basically import the re module, compile a pattern, identify a string,
create a list comprehension with a filter, slice out the result and
print to screen. I hope this helps.




More information about the Python-list mailing list