Python shlex.split(),忽略单引号

时间:2011-07-29 03:37:32

标签: python split quotes shlex

在Python中,我如何使用shlex.split()或类似的方法来拆分字符串,只保留双引号?例如,如果输入为"hello, world" is what 'i say',则输出为["hello, world", "is", "what", "'i", "say'"]

2 个答案:

答案 0 :(得分:16)

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'.''')

答案 1 :(得分:8)

您可以使用shlex.quotes来控制哪些字符将被视为字符串引号。您还需要修改shlex.wordchars,以使'isay保持一致。

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