Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'"].

like image 330
tekknolagi Avatar asked Jul 29 '11 03:07

tekknolagi


2 Answers

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'.''')
like image 166
Peter Lyons Avatar answered Nov 08 '22 13:11

Peter Lyons


You can use shlex.quotes to control which characters will be considered string quotes. You'll need to modify shlex.wordchars as well, to keep the ' with the i and the say.

import shlex

input = '"hello, world" is what \'i say\''
lexer = shlex.shlex(input)
lexer.quotes = '"'
lexer.wordchars += '\''

output = list(lexer)
# ['"hello, world"', 'is', 'what', "'i", "say'"]
like image 44
Matt Ball Avatar answered Nov 08 '22 11:11

Matt Ball