split a line, respecting double quotes
Sion Arrowsmith
siona at chiark.greenend.org.uk
Mon Jul 10 10:20:36 EDT 2006
Jim <jhefferon at smcvt.edu> 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.
>>> csv.reader(StringIO.StringIO('a b c "d e"'), delimiter=' ').next()
['a', 'b', 'c', 'd e']
It can't quite do the second one, but:
>>> csv.reader(StringIO.StringIO('a b c "d "" e"'), delimiter=' ').next()
['a', 'b', 'c', 'd " e']
isn't far off.
On the other hand, it's kind of a stupid solution. I'd really go with
shlex as someone suggested up thread.
--
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
More information about the Python-list
mailing list