在Python中,如何用空格分隔字符串(不包括双引号之间的空格)



我试图在Python中将文本拆分为一个列表,但我想排除文本&双引号之间的空格。简而言之,类似这样的东西:

def splitdq(text):
# do spliting stuff here...
test = 'The "quick brown fox" jumps over the "lazy dog."'
print(splitdq(test))
>>> ["The", "quick brown fox", "jumps", "over", "the", "lazy dog."]

我找到了一些解决方案,但它们要么保留了报价,要么就是不起作用。那么,在Python中有可能做到这一点吗?

您可以使用shlex类,它可以轻松地为等简单语法编写词法分析器

import shlex
test = 'The "quick brown fox" jumps over the "lazy dog."'
s = shlex.split(test)
for i in s:
print(i)

相关内容

最新更新