Quote-aware string splitting
Bengt Richter
bokr at oz.net
Tue Apr 26 03:38:46 EDT 2005
On Mon, 25 Apr 2005 19:40:44 -0700, Jeffrey Froman <jeffrey at fro.man> wrote:
>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']
>
>>> x = ' sspam " ssthe life of brianss " 42'
>>> [z.strip() for z in x.split('"')]
['sspam', 'ssthe life of brianss', '42']
Oops, note some spaces inside quotes near ss and missing double quotes in result.
Maybe (not tested beyond what you see):
>>> [r for r in [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.split('"'))] if r] or ['']
['sspam', '" ssthe life of brianss "', '42']
>>> x = ' "" "" '
>>> [r for r in [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.split('"'))] ifr] or ['']
['""', '""']
>>> x='""'
>>> [r for r in [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.split('"'))] ifr] or ['']
['""']
>>> x=''
>>> [r for r in [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.split('"'))] ifr] or ['']
['']
>>> [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.split('"'))]
['sspam', '" ssthe life of brianss "', '42']
Regards,
Bengt Richter
More information about the Python-list
mailing list