[Tutor] String matching in 1.5.2 problem

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed May 7 14:03:02 2003


On Wed, 7 May 2003, Daniel Nash wrote:

> I have a python 1.5.2 string matching problem.
>
> I have two lists of email addresses:
>
> list1 = ["dan@NO-SPAM.company.com","fred@NO-SPAM.company.com"]
>
> and another list made up from the contents extracted from an email's
> headers To:,Cc: & Bcc:
>
> list2 =[('', 'support@NO-SPAM.company.com'), ('jim',
> 'jim@NO-SPAM.company.com'), ('',
> 'fred@NO-SPAM.comapny.com')]
>
> I am trying to write a peice of code that will run in python 1.5.2 to return
> true if any element in list1 appears in list2.


Hi Daniel,


Reggie already showed that the 'string.find()' function can help you port
your code to Python 1.52.


By the way, we may be able to take advantage of dictionaries if we want to
see if one thing is an element in another thing.  If we represent list2 as
a dictionary,

###
addr_book = { 'support@NO-SPAM.company.com' : 1,
              'jim@NO-SPAM.company.com' : 1,
              'fred@NO-SPAM.company.com' : 1
            }
###


then when we try to see if something in list1 is in list2, that involves a
simple dictionary lookup:

###
for List1Head in List1:
    if addr_book.has_key(List1Head):     ## Written in Python 1.52 style
        print "Is Addressed to: ", List1Head
    else:
        print "Is NOT Addressed to: ", List1Head
###


This code ends up being simpler if we use a data structure like a
dictionary.  Nested loops make me dizzy, so anything that simplifies the
code can only be a good thing.  *grin*



Hope this helps!