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

Time:08-02

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)

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

Just define a list:

if str(p2eq) not in ["Ei", "gamma", "Piecewise"]:
    pass 
else:
    pass
  • Related