Splitting a line while keeping quoted items together

J

josh

I am working on a cmd.Cmd-based program, and normally could just split the string and get the right parts.

Now I have a case where I could have two or three words in the string that need to be grouped into the same thing.

Then I realized that I'm not the only person who has had to deal with this, and I'm wondering if my solution is the best one out there or if this is as ugly at it feels?

Code below
........

#x('Seattle 456') -> ('Seattle', '456')
#x('"Portland Alpha" 123') -> ('Portland Alpha', '123')
#x("'Portland Beta' 789') -> ('Portland Beta', '789')


def x(line):
res = []
append = False
appended = None
quote = None
for item in line.split():
if append:
if item.endswith(quote):
appended.append(item[:-1])
res.append(' '.join(appended))
quote = None
appended = None
append = False
else:
appended.append(item)
else:
if item[0] in ["'",'"']:
append = True
appended = [item[1:]]
quote = item[0]
else:
res.append(item)
return res
.......

This seem really ugly. Is there a cleaner way to do this? Is there a keyword I could search by to find something nicer?

Thanks,

Josh
 
S

Steven D'Aprano

I am working on a cmd.Cmd-based program, and normally could just split
the string and get the right parts.

Now I have a case where I could have two or three words in the string
that need to be grouped into the same thing.

Try shlex.split.
 

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

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top