在 Python 中,我如何使用shlex.split()
或类似于拆分字符串,只保留双引号?例如,如果输入是,"hello, world" is what 'i say'
那么输出将是["hello, world", "is", "what", "'i", "say'"]
。
问问题
21023 次
2 回答
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'.''')
于 2011-07-29T03:52:14.543 回答
8
您可以使用shlex.quotes
来控制哪些字符将被视为字符串引号。您还需要修改shlex.wordchars
,以保持'
与i
和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'"]
于 2011-07-29T03:45:02.037 回答