Is there a way I can compact this if-then statement involving string find() method?

Question:

I have this object I converted to a string. If the sting does not contain a string like "Ei" denoted with -1 param, then print/display the object.

if str(p2eq).find("Ei") == -1 and str(p2eq).find("gamma") == -1 and str(p2eq).find("Piecewise") == -1
and str(p2eq).find("li") == -1 and str(p2eq).find("erf") == -1 and str(p2eq).find("atan") == -1
and str(p2eq).find("Si") == -1 and str(p2eq).find("Ci") == -1 and str(p2eq).find("hyper") == -1
and str(p2eq).find("fresnel") == -1 and str(p2eq).find("Li") == -1:  
    display(p2eq.lhs)

I feel like there is a more efficient way to write this logic. I tried the code below, but it gives me several outputs when I just want one output.

for i in ["Ei", "gamma", "Piecewise"]:
     if str(p2eq).find(i) == -1:
          display(p2eq.lhs)
Asked By: nsc9

||

Answers:

Just define a list:

if str(p2eq) not in ["Ei", "gamma", "Piecewise"]:
    pass 
else:
    pass
Answered By: ygsg_aka

Make a set (or list) of all the keywords you’re looking for, then use any() with a generator expression to check if any of them are present.

You can also use needle not in haystack in place of the clunkier haystack.find(needle) == -1.

keywords = {
    "Ei",
    "gamma",
    "Piecewise",
    "li",
    "erf",
    "atan",
    "Si",
    "Ci",
    "hyper",
    "fresnel",
    "Li",
}

if not any(kw in str(p2eq) for kw in keywords):
    display(p2eq.lhs)
Answered By: John Kugelman

You can use the for-else construct instead to call display only if the loop does not break from any match:

s = str(p2eq)
for i in ["Ei", "gamma", "Piecewise"]:
     if i in s:
         break
else:
    display(p2eq.lhs)
Answered By: blhsing

An alternative solution based on sets. This also won’t trigger matches in atanx cases (it’s not a whole atan word as you can notice).

# define this somewhere once (globally)
keywords = {"Ei", "gamma", "Piecewise", "li", "erf", "atan", "Si", "Ci", "hyper", "fresnel", "Li"}

# split a string into words, build a set and intersect them
words = set(str(p2eq).split())
if not words.intersection(keywords):
    do_your_thing()

Answered By: westandskif
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.