在Python语言中,我如何使用shlex.split()或类似的工具来拆分字符串,只保留双引号?例如,如果输入为"hello, world" is what 'i say',则输出将为["hello, world", "is", "what", "'i", "say'"]。
发布于 2011-07-29 11:52:15
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-29 11:45:02
您可以使用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'"]https://stackoverflow.com/questions/6868382
复制相似问题