Shengqi Wang
Shengqi Wang

Reputation: 161

How do I search 2 or more strings inside another string in python?

I just started to teach myself Python, and I wanted to search an large array of strings for a couple of keywords. I tried using nested if statements but it's clunky and doesn't work.

Is there a easier way to do this? By the way, my array of strings is called tmp.

for i in range(0, len(idList)):
     for j in range(0, len(tmp)):
          if "apples" in tmp[j]: 
              if "bananas" in tmp[j]: 
                  if "peaches" in tmp[j]:
                      if "pears" in tmp[j]:
                          *Do something*

Upvotes: 0

Views: 63

Answers (2)

Celeo
Celeo

Reputation: 5682

From what you wrote it sounds like you're trying to find any of the keywords in the tmp list, not every in one element. If that's the case, then your code should instead be

for i in range(0, len(idList)):
    for j in range(0, len(tmp)):
        if "apples" in tmp[j]:
            *Do something*
        elif "bananas" in tmp[j]:
            *Do something*
        elif "peaches" in tmp[j]:
            *Do something*
        elif "pears" in tmp[j]:
            *Do something*

so you would do something (different or the same) in each of those conditions. If "apples" is in the current element in the list, then do something. Or, if "bananas" is in the element, then do something else.

To shorten your code, take a look at any:

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
     for element in iterable:
         if element:
             return True
     return False

This would make your code similar to Simeon's example, but replacing all for any.

Upvotes: 0

Simeon Visser
Simeon Visser

Reputation: 122326

Your code is equivalent to:

for i in range(0, len(idList)):
     for j in range(0, len(tmp)):
          if all(s in tmp[j] for s in ("apples", "bananas", "peaches", "pears")):
               *Do something*

which makes it a bit shorter. The all() function allows you to check multiple conditions and this function evaluates to true when all conditions are true.

Upvotes: 4

Related Questions