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

检查另一个字符串中是否存在多个字符串

  •  283
  • jahmax  · 技术社区  · 14 年前

    如何检查数组中的任何字符串是否存在于另一个字符串中?

    a = ['a', 'b', 'c']
    str = "a123"
    if a in str:
      print "some of the strings found in str"
    else:
      print "no strings found in str"
    

    代码不起作用,它只是显示我想要实现什么。

    13 回复  |  直到 14 年前
        1
  •  1
  •   balki    4 年前

    你可以用 any :

    a_string = "A string is more than its parts!"
    matches = ["more", "wholesome", "milk"]
    
    if any(x in a_string for x in matches):
    

    类似于检查 全部的 如果找到列表中的字符串,请使用 all 而不是 任何

        2
  •  1
  •   Jerald Cogswell    4 年前

    any() 如果你只想 True False

    如果你想要第一场比赛 作为默认值):

    match = next((x for x in a if x in str), False)
    

    如果要获取所有匹配项(包括重复项):

    matches = [x for x in a if x in str]
    

    matches = {x for x in a if x in str}
    

    如果要以正确的顺序获取所有不重复的匹配项:

    matches = []
    for x in a:
        if x in str and x not in matches:
            matches.append(x)