Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Splitting a line while keeping quoted items together (http://www.velocityreviews.com/forums/t954646-splitting-a-line-while-keeping-quoted-items-together.html)

josh@merchantconcepts.com 11-20-2012 12:05 AM

Splitting a line while keeping quoted items together
 
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

Steven D'Aprano 11-20-2012 01:09 AM

Re: Splitting a line while keeping quoted items together
 
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


All times are GMT. The time now is 07:06 PM.

Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57