0

I have a condition like:

str1 = "cat, dog, rat"
print( ("cat" not in str1) and ("dog" not in str1) and ("rat" not in str1)) #1
print(any(x not in str1 for x in ("cat","dog","rat"))) #2

The problem is #1 condition is too long if I add any others statements so I tranfer it to #2, but #2 return a opposite results, so how to write #1 simply in Python?

4daJKong
  • 1,825
  • 9
  • 21

2 Answers2

2

As @Sayse mentioned, you should use all instead of any

words_to_check = ["cat", "dog", "rat"]

str1 = "cat, dog, rat"

if all(word in str1 for word in words_to_check):
    print("All words are present")
else:
    print("Not all words are present")

Outputs:

All words are present
Antoine Delia
  • 1,728
  • 5
  • 26
  • 42
0

You could use re.search here with a regex alternation:

str1 = "cat, dog, rat"
regex = r'\b(?:' + r'|'.join(re.split(r',\s*', str1)) + r')\b'
if not re.search(regex, str1):
    print("MATCH")
else:
    print("NO MATCH")
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360