Yet another "split string by spaces preserving single quotes" problem

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue May 15 09:15:19 EDT 2012


On 2012年5月13日 14:14:58 -0700, Massi wrote:
> 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' 
problem"
>>> import shlex
>>> result = shlex.split(s, posix=True)
>>> result
['This', 'is', 'a', 'simple test:string which', 'shows', 'exactly my', 
'problem']
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 
my'", 'problem']
-- 
Steven


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /