代码之家  ›  专栏  ›  技术社区  ›  learner

返回列表的python筛选器字符串

  •  1
  • learner  · 技术社区  · 7 年前

    例如,示例输入:

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

    输出:

    ['Jungle', 'Guns N Roses']
    

    字符串- "Jungle" Guns N Roses . 所以输出的列表中有两个字符串。另一个示例输入:

    "How are (you, doing today)"
    

    输出:

    []
    

    说明: 我试着用split函数按单引号拆分,但意识到这不是正确的方法。你能帮我用python怎么做吗?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Rakesh    7 年前

    使用正则表达式--> 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']
    
        2
  •  2
  •   Partho63 BASANT KUMAR    7 年前

    你也可以这样试试。这是不使用任何库的最简单的编程方法。你可以试一试:

    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)
    

        3
  •  1
  •   Ashutosh Kumar    7 年前

    IMHO,使用regex的最佳方法是避免“贪婪”。

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

    这将寻找一个被引语包围的词。e、 它将跳过空的报价。

    我们用“?”来减少搜索的贪婪。