Combining multiple membership tests

To check if a string contains a substring, you can use "in" as follows:

if "abc" in str:
    print("yay")

      

And to check if a string contains one of two substrings, you can use "or" like so:

if "abc" in str or "def" in str:
    print("yay")

      

My question is if python can simplify this, for example:

if "abc" or "def" in str:
    print("yay")

      

I know this won't work as intended because it will always evaluate to true. (Python will check at least one of the two statements, or

  • "abc"
  • "def" to str

is true and "abc" will always be true)

Having said that, you still need to check for a condition like this other than this, quite verbose, method:

if "abc" in str or "def" in str:
    print("yay")

      

+3


source to share


3 answers


if any(word in sentence for word in {"abc", "def"}):
    print("yay")

      



+4


source


Put them in an array and do:

if any(x in word for x in a):

      



An answer was given here Check if multiple lines exist on another line

+4


source


If your question is, is there a way to check if any string exists in the specified list of strings in a larger string. We can use the function any()

together with generator expressions

for this.

Example -

>>> s = "Hello World Bye Abcd"
>>> l = ["Hello","Blah"]
>>> l1 = ["Yes","No"]
>>> any(li in s for li in l)
True
>>> any(li in s for li in l1)
False

      

+2


source







All Articles