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

10 投票
2 回答
23189 浏览
提问于 2025-04-16 22:29

在Python中,我想用shlex.split()或者类似的方法来分割字符串,但只保留双引号。比如,如果输入是"hello, world" is what 'i say',那么输出应该是["hello, world", "is", "what", "'i", "say'"]

2 个回答

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

撰写回答