Categories
Python Answers

How to check for valid email address with Python?

Spread the love

Sometimes, we want to check for valid email address with Python.

In this article, we’ll look at how to check for valid email address with Python.

How to check for valid email address with Python?

To check for valid email address with Python, we can use a regex and the regex search method to check whether a string is a valid email string.

For instance, we write:

import re


def valid_email(email):
    return bool(re.search(r"^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$", email))


print(valid_email('abc@abc.com'))
print(valid_email('abc'))

to define the valid_email function to check if email is a valid email address.

We check for the characters before the @ with ^[\w\.\+\-]+. The pattern matches dots and words.

And we check for @ with \@

We check for characters after the @ with [\w]+\.[a-z]{2,3}$. The pattern matches dots and words with the domain suffix at the end.

Therefore, we should see:

True
False

printed since we have a valid and an invalid email string respectively.

Conclusion

To check for valid email address with Python, we can use a regex and the regex search method to check whether a string is a valid email string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *