Gilles Ganault <nos...@nospam.com> writes:

> I'd like to go through a list of e-mail addresses, and extract those
> that belong to well-known ISP's. For some reason I can't figure out,
> Python shows the whole list instead of just e-mails that match:
> 
> ======= script
> test = "t...@gmail.com"
> isp = ["gmail.com", "yahoo.com"]
> for item in isp:
>       if test.find(item):
>               print item
> ======= output
> gmail.com
> yahoo.com
> ======= 
> 
> Any idea why I'm also getting "yahoo.com"?

You've had answers on the “why” question.

Here's a suggestion for a better way that doesn't involve ‘find’:

    >>> known_domains = ["example.com", "example.org"]
    >>> test_address = "t...@example.com"
    >>> for domain in known_domains:
    ...     if test_address.endswith("@" + domain):
    ...         print domain
    ... 
    example.com
    >>> 

If all you want is a boolean “do any of these domains match the
address”, it's quicker and simpler to feed an iterator to ‘any’
(first introduced in Python 2.5), which short-cuts by exiting on the
first item that produces a True result:

    >>> known_domains = ["example.com", "example.org"]
    >>> test_address = "t...@example.com"
    >>> any(test_address.endswith("@" + domain) for domain in known_domains)
    True
    >>> test_address = "tin...@example.net"
    >>> any(test_address.endswith("@" + domain) for domain in known_domains)
    False

-- 
 \      “For my birthday I got a humidifier and a de-humidifier. I put |
  `\  them in the same room and let them fight it out.” —Steven Wright |
_o__)                                                                  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to