0

Here is my below code that works fine. 'cluster_name' is a string variable that will hold some text.

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

i was looking to make the if condition even more simpler , something like this:

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

is there a simpler way to do this?

1
  • 1
    Watch out...They don't mean the same thing... Commented Oct 25, 2018 at 20:18

2 Answers 2

2

Your approach looks fine, but doesn't generalize well (imagine if you had to check ten substrings instead of just two). Try any.

substrings = ['abc', 'xyz']
if any(substr not in cluster_name for substr in substrings):
    print("true")
else:
    print("false")
Sign up to request clarification or add additional context in comments.

2 Comments

OP: Just to confirm, this only fails if both abc and xyz are present in cluster_name. Is this what you expect?
'cluster_name' will contain either 'abc' or 'xyz' at a time
1
import re
print (re.search('abc|xyz',cluster_name) is not None)

is simpler. It does not need if or else; you can extend the search string as long as you want (although within reasonable limits, no doubt). re.search returns None if the regex does not match and you want the inverse of that, hence not None.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.