Skip to main content
 首页 » 编程设计

python过滤字符串以返回列表

2025年05月04日32jiqing9006

我想过滤给定的句子并提取所有被单引号括起来的字符串并返回一个列表。

例如,示例输入:

"Welcome to 'Jungle', is a song by American rock band 'Guns N Roses' released in 1987." 

输出:

['Jungle', 'Guns N Roses'] 

解释: String - "Jungle" 是用单引号括起来的,所以我们要挑这个。同样 - Guns N Roses。所以输出的列表中有 2 个字符串。另一个示例输入:

"How are (you, doing today)" 

输出:

[] 

解释: 单引号之间没有任何内容,因此返回空列表。 我尝试使用 split 函数按单引号拆分,但意识到这不是正确的方法。你能帮我看看如何在 python 中做到这一点吗?

请您参考如下方法:

使用正则表达式 --> re.findall。

例如:

import re 
 
s = "Welcome to 'Jungle', is a song by American rock band 'Guns N Roses' released in 1987." 
print(re.findall(r"'(.*?)'", s)) 

输出:

['Jungle', 'Guns N Roses']