split a line, respecting double quotes

Steven Bethard steven.bethard at gmail.com
Fri Jul 7 17:58:31 EDT 2006


Jim wrote:
> Is there some easy way to split a line, keeping together double-quoted
> strings?
> 
> I'm thinking of
>   'a b c "d e"'  --> ['a','b','c','d e']
> .  I'd also like
>   'a b c "d \" e"'  --> ['a','b','c','d " e']
> which omits any s.split('"')-based construct that I could come up with.

 >>> import shlex
 >>> shlex.split('a b c "d e"')
['a', 'b', 'c', 'd e']
 >>> shlex.split(r'a b c "d \" e"')
['a', 'b', 'c', 'd " e']

Note that I had to use a raw string in the latter case because otherwise 
there's no real backslash in the string::

 >>> 'a b c "d \" e"'
'a b c "d " e"'
 >>> r'a b c "d \" e"'
'a b c "d \\" e"'

STeVe



More information about the Python-list mailing list