更好的方法来查看一个变量中的两个不同的字符串?

时间:2018-02-25 23:59:37

标签: python python-3.6

我有以下代码:

if <one-string> in x and <another-string> in x:
    <do something>

我讨厌在两个单独的步骤中将两个值比较到同一个变量的重复。但我无法迭代字符串,因为我仍然最终得到两个布尔值,然后必须比较最终的布尔值。有这样做的pythonic方法吗?

2 个答案:

答案 0 :(得分:0)

您可以使用set()

执行此操作
your_strings = ['one-string', 'another-string']
if len(set(your_strings) & set(x)):
    # do something

答案 1 :(得分:0)

只需使用适当的功能将所有布尔值合并为一个。

if all(s in x for s in ('foo', 'bar')):
   ...

if not any(s in x for s in ('foo', 'bar')):
   ...