Quote-aware string splitting

Jeffrey Froman jeffrey at fro.man
Mon Apr 25 22:40:44 EDT 2005


J. W. McCall wrote:

> For example, given the string:
> 
> 'spam "the life of brian" 42'
> 
> I'd want it to return:
> 
> ['spam', 'the life of brian', '42']

The .split() method of strings can take a substring, such as a quotation
mark, as a delimiter. So a simple solution is:

>>> x = 'spam "the life of brian" 42'
>>> [z.strip() for z in x.split('"')]
['spam', 'the life of brian', '42']


                        Jeffrey



More information about the Python-list mailing list