How, in Python, can I use shlex.split()
or similar to split strings, preserving only double quotes? For example, if the input is "hello, world" is what 'i say'
then the output would be ["hello, world", "is", "what", "'i", "say'"]
.
如何在Python中使用shlex.split()或类似于拆分字符串,只保留双引号?例如,如果输入是“hello, world”,那么输出将是[“hello, world”,“is”,“what”,“i”,“say”]。
2 个解决方案
#1
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'.''')
#2
7
You can use shlex.quotes
to control which characters will be considered string quotes. You'll need to modify shlex.wordchars
as well, to keep the '
with the i
and the say
.
您可以使用shlex。用于控制哪些字符将被视为字符串引号的引号。您需要修改shlex。还有文字游戏,以保持“我”和“说”。
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'"]
#1
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'.''')
#2
7
You can use shlex.quotes
to control which characters will be considered string quotes. You'll need to modify shlex.wordchars
as well, to keep the '
with the i
and the say
.
您可以使用shlex。用于控制哪些字符将被视为字符串引号的引号。您需要修改shlex。还有文字游戏,以保持“我”和“说”。
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'"]