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

M

Massi

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:

splitter = re.compile("(?=\s|^)('[^']+') | ('[^']+')(?=\s|$)")

temp = [t for t in splitter.split(s) if t not in [None, '']]
print temp
t = []
for i, p in enumerate(temp) :
for x in ([p] if (p[0] == "'" and p[1] == "'") else p.split('
')) :
t.append(x)

But it does not handle "colon" case.
Any hints? Thanks in advance!
 
S

Steven D'Aprano

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!
['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']
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top