views:

89

answers:

5

How can I check if any of the strings in an array exists in another string?

Like:

a = ['a', 'b', 'c']
str = "a123"
if a in str:
  print "some of the strings found in str"
else:
  print "no strings found in str"

That code doesn't work, it's just to show what I want to achieve.

+9  A: 

You can use any:

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

Similarly to check if all the strings from the list are found, use all instead of any.

Mark Byers
Thanks! will accept your answer in a few minutes when it allow me to.
jahmax
A: 

You need to iterate on the elements of a.

a = ['a', 'b', 'c']
str = "a123"
found_a_string = FALSE
for item in a:    
    if a in str:
        found_a_string = TRUE

if found_a_string:
    print "found a match"
else:
    print "no match found"
Seamus Campbell
Yes i knew how to do that but compared to Marks answer, that's horrible code.
jahmax
Only if you understand Mark's code. The problem you were having is that you weren't examining the elements of your array. There are a lot of terse, pythonic ways to accomplish what you want that would hide the essence of what was wrong with your code.
Seamus Campbell
A: 
a = ['a', 'b', 'c']
str =  "a123"

a_match = [True for match in a if match in str]

if True in a_match:
  print "some of the strings found in str"
else:
  print "no strings found in str"
mluebke
A: 

You should be careful if the strings in a or str gets longer. The straightforward solutions take O(S*(A^2)), where S is the length of str and A is the sum of the lenghts of all strings in a. For a faster solution, look at Aho-Corasick algorithm for string matching, which runs in linear time O(S+A).

jbernadas
A: 

You shouldn't use str as a name:

>>> str(7)
'7'
>>> str = 'joe'
>>> str(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
pillmuncher
[QUOTE]: "That code doesn't work, it's just to show what I want to achieve."
jahmax