【问题标题】:simpler way to check if two different strings are in a third string in python更简单的方法来检查两个不同的字符串是否在python的第三个字符串中
【发布时间】:2019-03-30 13:08:21
【问题描述】:

这是我下面的代码,可以正常工作。 'cluster_name' 是一个字符串变量,可以保存一些文本。

if 'abc' not in cluster_name or 'xyz' not in cluster_name:
    print "true"
else:
    print "false"

我希望使if 条件更简单,如下所示:

if 'abc' or 'xyz' not in cluster_name:
    print "true"
else:
    print "false"

有没有更简单的方法来做到这一点?

【问题讨论】:

  • 当心...它们的意思不一样...

标签: python string python-2.7


【解决方案1】:

您的方法看起来不错,但不能很好地概括(想象一下,如果您必须检查十个子字符串而不仅仅是两个)。试试any

substrings = ['abc', 'xyz']
if any(substr not in cluster_name for substr in substrings):
    print("true")
else:
    print("false")

【讨论】:

  • OP:确认一下,只有当abcxyz 都存在于cluster_name 时才会失败。这是你所期望的吗?
  • 'cluster_name' 将一次包含 'abc' 或 'xyz'
【解决方案2】:
import re
print (re.search('abc|xyz',cluster_name) is not None)

更简单。它不需要ifelse;您可以根据需要扩展搜索字符串(尽管在合理的范围内,毫无疑问)。 re.search 返回 None 如果正则表达式 not 匹配并且你想要它的逆,因此 not None

【讨论】:

    猜你喜欢
    • 2013-02-10
    • 1970-01-01
    • 2021-11-02
    • 2013-02-12
    • 2013-07-22
    • 2018-06-26
    • 1970-01-01
    • 2023-04-09
    • 2015-07-07
    相关资源
    最近更新 更多