Eli Fulkerson .com HomeProjectsSplit-respect-singlequotes
 

Split that Respects Singlequotes

Description:

This is a variation on the normal 'split' function that ignores instances of the value that you are splitting on (normally a space, for instance) if that split value happens to be between a pair of single quotes. This is useful for parsing command line arguments.

Platform:

  • no platform specific code, should work anywhere that has Python
  • Language:

  • Python
  • License:

  • This function is trivial. I am placing it in the public domain, do whatever you want with it.
  • Code:

    def split_respect_singlequotes( data, splitval=" "):
        """
        This function returns a list of arguments in data, but ignoring
        the splitval token when it is found within single quotes.
        
        For instances, it allows "cast 'magic missile' 'big ogre'" to
        be returned as three arguments.  cast, 'magic missile' and 'big ogre'
        """
        tmp = []
        buffer = ""
        quotes = 0
        for counter in range(0, len(data)):
            if data[counter] == "'":
                quotes = (quotes + 1) % 2
            elif quotes == 0 and data[counter] == splitval:
                tmp.append(buffer)
                buffer = ""
            else:
                buffer = buffer + data[counter]
        tmp.append(buffer)
        return tmp

    Source code without formatting