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

tek*_*agi 10 python quotes split shlex

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

Pet*_*ons 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'.''')
Run Code Online (Sandbox Code Playgroud)


Mat*_*all 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'"]
Run Code Online (Sandbox Code Playgroud)