python过滤器字符串返回列表

时间:2019-03-13 06:43:32

标签: python regex string

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

例如,示例输入:

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

输出:

['Jungle', 'Guns N Roses']

说明: 字符串-"Jungle"用单引号引起来,因此我们需要选择它。同样-Guns N Roses。因此,输出在其列表中有2个字符串。另一个示例输入:

"How are (you, doing today)"

输出:

[]

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

3 个答案:

答案 0 :(得分:2)

使用正则表达式-> 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']

答案 1 :(得分:2)

您也可以尝试这种方式。这是不使用任何库的最简单的编程方法。您可以尝试一下:

full_string = input("Enter String: ")
quoted_strings = []

start = 0
quoted_string = ""
for letter in full_string:
    if letter == "'" and start == 0:
        start = 1
    elif letter == "'" and start == 1:
        quoted_strings.append(quoted_string)
        quoted_string = ""
        start = 0
    elif start == 1:
        quoted_string += letter
    else:
        pass

print("Entered Full String: " + full_string)
print("Quoted Strings: ", quoted_strings)

尽管接受答案只是为了好玩。祝您编码愉快!

答案 2 :(得分:1)

恕我直言,使用正则表达式的最佳方法是避免“贪婪”。

import re
a = "'Jungle', is a song by American rock band 'Guns N Roses'"]
re.findall(r"'(.+?)'", a)

这会寻找一个用引号引起来的单词。例如它将跳过空的报价。 如果要包含空引号,请使用*代替+。

我们正在使用'?'减少搜索的贪婪程度。

相关问题