仅加入一部分字符串列表取决于它在python中的值

问题描述 投票:1回答:1

例如,我有一个字符串列表:

['this', 'is', 'an', 'example', 'of', 'list', 'of', 'strings']

我只想提取其中一些单词,并且仅当它们之间有引号时才将它们连接在一起

所以,如果我的清单是...

['I', 'only', 'want', '"this', 'part"', 'of', 'the', 'list']

它将返回“这部分”,因为这是中间有引号的部分。

I tried using str.find("\"")

但是它只找到第一个引号,所以我不能真正使用太多,有人对如何执行此操作有任何想法吗?我感谢所有帮助:))

python
1个回答
3
投票

您可以在re.findall中使用以下模式:

l = ['I', 'only', 'want', '"this', 'part"', 'of', 'the', 'list', '"another', 'example"']

re.findall(r'\"(.*?)\"', ' '.join(l))
# ['this part', 'another example']
© www.soinside.com 2019 - 2024. All rights reserved.