'How to abbreviate this condition in Python? [duplicate]
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?
Solution 1:[1]
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
Solution 2:[2]
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")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Antoine Delia |
| Solution 2 | Tim Biegeleisen |
