【问题标题】:How to split a string by spaces excluding ones between double quotes in Python? [duplicate]如何用空格分割字符串,不包括Python中双引号之间的空格? [复制]
【发布时间】:2021-03-26 11:15:06
【问题描述】:

我正在尝试将文本拆分为 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 中做到这一点?

【问题讨论】:

标签: python arrays python-3.x string list


【解决方案1】:

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

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

【讨论】:

  • 谢谢!这正是我想要的
  • 不客气@bemxio
猜你喜欢
  • 2013-03-03
  • 2016-12-26
  • 2014-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-25
相关资源
最近更新 更多