Split a string by spaces — preserving quoted substrings — in Python

后端 未结 16 871
心在旅途
心在旅途 2020-11-22 15:05

I have a string which is like this:

this is \"a test\"

I\'m trying to write something in Python to split it up by space while ignoring spac

16条回答
  •  深忆病人
    2020-11-22 15:35

    To preserve quotes use this function:

    def getArgs(s):
        args = []
        cur = ''
        inQuotes = 0
        for char in s.strip():
            if char == ' ' and not inQuotes:
                args.append(cur)
                cur = ''
            elif char == '"' and not inQuotes:
                inQuotes = 1
                cur += char
            elif char == '"' and inQuotes:
                inQuotes = 0
                cur += char
            else:
                cur += char
        args.append(cur)
        return args
    

提交回复
热议问题