Splitting a line while keeping quoted items together

Discussion in 'Python' started by josh@merchantconcepts.com, Nov 20, 2012.

  1. Guest

    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
    , Nov 20, 2012
    #1
    1. Advertising

  2. 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
    Steven D'Aprano, Nov 20, 2012
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Nik Coughin
    Replies:
    2
    Views:
    586
    Jeff Thies
    Jul 28, 2004
  2. Fons Rave

    Keeping words together

    Fons Rave, May 9, 2006, in forum: HTML
    Replies:
    16
    Views:
    7,670
    Fons Rave
    May 10, 2006
  3. mosscliffe

    Splitting a quoted string.

    mosscliffe, May 16, 2007, in forum: Python
    Replies:
    5
    Views:
    311
    Gerard Flanagan
    May 16, 2007
  4. CBlair1986
    Replies:
    4
    Views:
    127
    CBlair1986
    Nov 18, 2006
  5. Tim Chase
    Replies:
    0
    Views:
    156
    Tim Chase
    Nov 20, 2012
Loading...

Share This Page