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?
Answers:
array = ['12', '13', '14']
string = '12345678'
for item in array:
print(item in string)
You can use the "in" operator
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
here is simple solution using in
operator.
Steps –
- Iterating over each element of an array.
- Checking whether element is present or Not.
- If present the print True and break.
l = ['12','13','14']
s = '123456789'
for i in l:
if i in s:
print(True)
break;
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]
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?
array = ['12', '13', '14']
string = '12345678'
for item in array:
print(item in string)
You can use the "in" operator
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
here is simple solution using in
operator.
Steps –
- Iterating over each element of an array.
- Checking whether element is present or Not.
- If present the print True and break.
l = ['12','13','14']
s = '123456789'
for i in l:
if i in s:
print(True)
break;
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]