[Tutor] Searching for a substring within a list

Gregor Lingl glingl@aon.at
Sat Mar 8 07:54:01 2003


Daniel Nash schrieb:

>
>
>
> I have a list of email addresses :
>
> list1 = ["dan@company.com","fred@company.com"]
>
> and another list made up from the contents extracted from an email 
> headers To:,Cc: & Bcc:
>
> list2 =[('', 'support@company.com'), ('jim', 'jim@company.com'), ('', 
> 'fred@comapny.com')]
>
> I want to write a peice of code to return true if any element in the 
> first list appears as a substring of any element in the second list.
>
> for List1Head in List1List:
>    for List2Head in List2:
>        if string.find(List1Head, List2Head) >= 0:
>            print "YEP ", ListHead, " Is in the list"
>
> This code doesn't work "TypeError: expected a character buffer object"
> I think this means that I need to convert value of List2head to a 
> string. But this code is very messy.
>
> Is there a better way to solve my problem?
>
Hi Daniel!

If  I understand your question correctly, it goes (for example) like this
(I'v inserted a print-statement, to show better waht's going on):

 >>> list1 = ["dan@company.com","fred@company.com"]
 >>> list2 =[('', 'support@company.com'), ('jim', 'jim@company.com'), 
('', 'fred@company.com')]
 >>> for List1Head in list1:
...     for List2Head in list2:
...         print List1Head, List2Head
...         if List1Head in List2Head:
...             print "YEP ", List1Head, " Is in the list"
...
dan@company.com ('', 'support@company.com')
dan@company.com ('jim', 'jim@company.com')
dan@company.com ('', 'fred@company.com')
fred@company.com ('', 'support@company.com')
fred@company.com ('jim', 'jim@company.com')
fred@company.com ('', 'fred@company.com')
YEP  fred@company.com  Is in the list
 >>>

You have to test if a given email-adress (of list1)
 is *element* of one of the *tuples* in list2. This can be done
with the boolean operator in.

If you wanted to test, if the adress is contained in the string, which is
the second element of the tuple, you would have to use it,
namely List2Head[1] (and test via find)

HTH, Gregor