is there any lib can split string in this way?

Discussion in 'Python' started by Leo Jay, Jan 9, 2006.

  1. Leo Jay

    Leo Jay Guest

    I want to split a string like this:
    'abc def "this is a test" ok'
    into:
    ['abc', 'def', 'this is a test', 'ok']

    is there any lib meet my need?

    thanks

    --
    Best Regards,
    Leo Jay
     
    Leo Jay, Jan 9, 2006
    #1
    1. Advertising

  2. Leo Jay

    Guest

    This has been asked not long ago. the shlex module as well as csv
    module both should be able to handle it. for this simple case
    shlex.split() seems to be the easiest.

    Leo Jay wrote:
    > I want to split a string like this:
    > 'abc def "this is a test" ok'
    > into:
    > ['abc', 'def', 'this is a test', 'ok']
    >
    > is there any lib meet my need?
    >
    > thanks
    >
    > --
    > Best Regards,
    > Leo Jay
     
    , Jan 9, 2006
    #2
    1. Advertising

  3. On Mon, 9 Jan 2006 13:59:44 +0800, Leo Jay <> wrote:

    >I want to split a string like this:
    >'abc def "this is a test" ok'
    >into:
    >['abc', 'def', 'this is a test', 'ok']
    >
    >is there any lib meet my need?
    >

    Narrowly interpreting your requirements (only quotes are with
    double quotes (never containing escaped same) and strip quotes off)
    and tested only as you see ;-)

    >>> import re
    >>> rx = re.compile(r'"([^"]*)"|(\w+)')
    >>> s = 'abc def "this is a test" ok'
    >>> [a or b for a,b in rx.findall(s)]

    ['abc', 'def', 'this is a test', 'ok']

    Regards,
    Bengt Richter
     
    Bengt Richter, Jan 9, 2006
    #3
    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. jack
    Replies:
    1
    Views:
    525
    Roedy Green
    Apr 3, 2004
  2. Carlos Ribeiro
    Replies:
    11
    Views:
    741
    Alex Martelli
    Sep 17, 2004
  3. est
    Replies:
    1
    Views:
    664
    Diez B. Roggisch
    Feb 16, 2008
  4. Sam Kong
    Replies:
    5
    Views:
    277
    Rick DeNatale
    Aug 12, 2006
  5. Stanley Xu
    Replies:
    2
    Views:
    712
    Stanley Xu
    Mar 23, 2011
Loading...

Share This Page