Search code examples
pythonsplitquotesshlex

Python shlex.split(), ignore single quotes


How, in Python, can I use shlex.split() or similar to split strings, preserving only double quotes? For example, if the input is "hello, world" is what 'i say' then the output would be ["hello, world", "is", "what", "'i", "say'"].


Solution

  • import shlex
    
    def newSplit(value):
        lex = shlex.shlex(value)
        lex.quotes = '"'
        lex.whitespace_split = True
        lex.commenters = ''
        return list(lex)
    
    print newSplit('''This string has "some double quotes" and 'some single quotes'.''')