Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I catch "split" exceptions in python?

Tags:

python

I am trying to parse a list of email addresses to remove the username and '@' symbol only leaving the domain name.

Example: [email protected] Desired output: gmail.com

I have accomplished this with the following code:

for row in cr: 
    emailaddy = row[0]
    (emailuser, domain) = row[0].split('@')
    print domain

but my issue is when I encounter a improperly formatted email address. For example if the row contains "aaaaaaaaa" (instead of a valid email address) the program crashes with the error

(emailuser, domain) = row[0].split('@')
ValueError: need more than 1 value to unpack. 

(as you would expect) Rather than check all the email addresses for their validity, I would rather just not update grab the domain and move on to the next record. How can I properly handle this error and just move on?

So for the list of:

[email protected]
[email protected]
youououou
[email protected]

I would like the output to be:

gmail.com
hotmail.com

yahoo.com

Thanks!

like image 470
Bill Swearingen Avatar asked Feb 28 '12 05:02

Bill Swearingen


People also ask

What split () do in Python?

Definition and Usage. The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you handle two exceptions in Python?

By handling multiple exceptions, a program can respond to different exceptions without terminating it. In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.

How do I get a list of exceptions in Python?

Try and Except Statement – Catching all Exceptions Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.

What does the split () method return from a list of words?

Description. Python string method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.


2 Answers

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']
>>>
like image 91
RanRag Avatar answered Feb 08 '23 16:02

RanRag


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 ('').

like image 42
glglgl Avatar answered Feb 08 '23 16:02

glglgl