Check if elements from array are in a string

Question:

I want to check if there is one of my elements in my array in an string
Like: ['12', '13', '14'] is my array and my string is '123456789' and if one of my Array elements is in my string then it should be True

Is there a way to do this?

Asked By: user13058586

||

Answers:

array = ['12', '13', '14']
string = '12345678'
for item in array:
    print(item in string)

You can use the "in" operator

Answered By: Devworm

Chester’s comment have it all.

But if you’d like a more readable version, something like that might help :

def include(lst = ['12','13','14'], search_string = '123456789'):
  for e in lst:
    if e in search_string:
      print(f'found {e}')
      return True
  return False
Answered By: Loïc

here is simple solution using in operator.
Steps –

  1. Iterating over each element of an array.
  2. Checking whether element is present or Not.
  3. If present the print True and break.
l = ['12','13','14']
s = '123456789'

for i in l:
    if i in s:
        print(True)
        break;
Answered By: anonymous

In a line, you can get a mask array of your array:

l = ['12','13','14']
s = '123456789'
print([(X in s) for X in l])

This prints:

[True, False, False]
Answered By: Buzz
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.