steve+comp.lang.python at pearwood
May 15, 2012, 6:15 AM
Post #3 of 3
On Sun, 13 May 2012 14:14:58 -0700, Massi wrote:
Re: Yet another "split string by spaces preserving single quotes" problem
[In reply to]
> Hi everyone,
> I know this question has been asked thousands of times, but in my case I
> have an additional requirement to be satisfied. I need to handle
> substrings in the form 'string with spaces':'another string with spaces'
> as a single token; I mean, if I have this string:
> s ="This is a 'simple test':'string which' shows 'exactly my' problem"
> I need to split it as follow (the single quotes must be mantained in the
> splitted list):
> [."This", "is", "a", "'simple test':'string which'", "shows", "'exactly
> my'", "problem"]
> Up to know I have written some ugly code which uses regular expression:
And now you have two problems *wink*
> Any hints? Thanks in advance!
>>> s = "This is a 'simple test':'string which' shows 'exactly my'
>>> import shlex
>>> result = shlex.split(s, posix=True)
['This', 'is', 'a', 'simple test:string which', 'shows', 'exactly my',
Then do some post-processing on the result:
>>> [."'"+s+"'" if " " in s else s for s in result]
['This', 'is', 'a', "'simple test:string which'", 'shows', "'exactly