split string saving screened spaces

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Sergey

    #1

    split string saving screened spaces

    Which module to use to do such thing:

    "-a -b -c '1 2 3'" -> ["-a", "-b", "-c", "'1 2 3'"]

    (i have string, need to pass it to getopt)


  • Giovanni Bajo

    #2
    Re: split string saving screened spaces

    Sergey wrote:
    [color=blue]
    > Which module to use to do such thing:[/color]
    [color=blue]
    > "-a -b -c '1 2 3'" -> ["-a", "-b", "-c", "'1 2 3'"][/color]

    [color=blue][color=green][color=darkred]
    >>> import shlex
    >>> shlex.split("-a -b -c '1 2 3'")[/color][/color][/color]
    ['-a', '-b', '-c', '1 2 3']

    --
    Giovanni Bajo


    Comment

    • bonono@gmail.com

      #3
      Re: split string saving screened spaces


      Sergey wrote:[color=blue]
      > Which module to use to do such thing:
      >
      > "-a -b -c '1 2 3'" -> ["-a", "-b", "-c", "'1 2 3'"]
      >
      > (i have string, need to pass it to getopt)[/color]
      seems like CSV except that the seperator is space. You may check to see
      if the CSV module can take space as delimiter.

      Comment

      • Paul McGuire

        #4
        Re: split string saving screened spaces

        Pyparsing has built-in quoted string support.


        from pyparsing import OneOrMore,Word, alphanums,quote dString

        item = Word('-',alphanums) | quotedString | Word(alphanums)
        items = OneOrMore(item)

        print items.parseStri ng( "-a -b -c '1 2 3' -d 5 -e zork2000" )

        gives:
        ['-a', '-b', '-c', "'1 2 3'", '-d', '5', '-e', 'zork2000']


        Download pyparsing at http://pyparsing.sourceforge.net.

        -- Paul

        Comment

        Working...