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

新手上路,请多包涵

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

喜欢:

 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"

该代码不起作用,它只是为了显示我想要实现的目标。

原文由 jahmax 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 785
2 个回答

您可以使用 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 而不是 any

原文由 Mark Byers 发布,翻译遵循 CC BY-SA 4.0 许可协议

any() 是迄今为止最好的方法,如果你想要的只是 TrueFalse ,但如果你的字符串/字符串想知道具体匹配哪个几件事。

如果您想要第一个匹配项(默认为 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)

原文由 zondo 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题