How do I catch "split" exceptions in python?

You can just filter out the address which does not contain @.

>>> [mail.split('@')[1] for mail in mylist if '@' in mail]
['gmail.com', 'hotmail.com', 'yahoo.com']
>>>

What about

splitaddr = row[0].split('@')
if len(splitaddr) == 2:
    domain = splitaddr[1]
else:
    domain = ''

This even handles cases like aaa@bbb@ccc and makes it invalid ('').


You want something like this?

try:
    (emailuser, domain) = row[0].split('@')
except ValueError:
    continue

Try this

In [28]: b = ['[email protected]',
 '[email protected]',
 'youououou',
 '[email protected]']

In [29]: [x.split('@')[1] for x in b if '@' in x]
Out[29]: ['gmail.com', 'hotmail.com', 'yahoo.com']

Tags:

Python