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



如何在Python中使用shlex.split()或类似的分割字符串,仅保留双引号?例如,如果输入是"hello, world" is what 'i say',那么输出将是["hello, world", "is", "what", "'i", "say'"]

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

您可以使用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'"]

相关内容

  • 没有找到相关文章

最新更新