Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Splitting a line while keeping quoted items together

Reply
Thread Tools

Splitting a line while keeping quoted items together

 
 
josh@merchantconcepts.com
Guest
Posts: n/a
 
      11-20-2012
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
 
Reply With Quote
 
 
 
 
Steven D'Aprano
Guest
Posts: n/a
 
      11-20-2012
On Mon, 19 Nov 2012 16:05:30 -0800, josh wrote:

> 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.



--
Steven
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Splitting a line while keeping quoted items together Tim Chase Python 0 11-20-2012 01:20 AM
Re: Splitting text at whitespace but keeping the whitespace in thereturned list MRAB Python 3 01-26-2010 11:36 PM
Problem while splitting the line using a delimiter and pushing itinto an array Prasanth C++ 4 11-22-2008 05:10 AM
Splitting string into array keeping delimiters Gary C40 Ruby 6 12-16-2007 10:46 AM
Splitting a quoted string. mosscliffe Python 5 05-16-2007 01:13 PM



Advertisments