在Python中,我如何使用shlex.split()
或类似的方法来拆分字符串,只保留双引号?例如,如果输入为"hello, world" is what 'i say'
,则输出为["hello, world", "is", "what", "'i", "say'"]
。
答案 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
,以使'
与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'"]