split a string with quoted parts into list

Scott David Daniels Scott.Daniels at Acm.Org
Thu Mar 10 13:21:08 CET 2005


oliver wrote:
> i'm experimanting with imaplib and came across stringts like
>     (\HasNoChildren) "." "INBOX.Sent Items"
> in which the quotes are part of the string.
> 
> now i try to convert this into a list. assume the string is in the variable 
> f, then i tried
>     f.split()
> but i end up with
>     ['(\\HasNoChildren)', '"."', '"INBOX.Sent', 'Items"']
> so due to the sapce in "Sent Items" its is sepearted in two entries, what i 
> don't want.

> is there another way to convert a string with quoted sub entries into a list 
> of strings?

First break into strings, then space-split the non-strings.

     def splitup(somestring):
         gen = iter(somestring.split('"'))
         for unquoted in gen:
             for part in unquoted.split():
                 yield part
             yield gen.next().join('""')

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list