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

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

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

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:
    606
    Roedy Green
    Apr 3, 2004
  2. Carlos Ribeiro
    Replies:
    11
    Views:
    966
    Alex Martelli
    Sep 17, 2004
  3. ashu
    Replies:
    7
    Views:
    484
    David Resnick
    Jan 26, 2006
  4. Replies:
    9
    Views:
    1,033
    benben
    Mar 17, 2006
  5. est
    Replies:
    1
    Views:
    827
    Diez B. Roggisch
    Feb 16, 2008
  6. Sam Kong
    Replies:
    5
    Views:
    546
    Rick DeNatale
    Aug 12, 2006
  7. Stanley Xu
    Replies:
    2
    Views:
    1,055
    Stanley Xu
    Mar 23, 2011
  8. Andries

    is there a way ..... any way

    Andries, Apr 26, 2004, in forum: Perl Misc
    Replies:
    27
    Views:
    548
    Robin
    Apr 27, 2004
Loading...