Validate Email Format in Python

Validate whether a string matches a basic email address pattern.

IntermediateConditional ProgramsExample 20 of 20
validate-email-format.py
1# Program to validate email format using regex
2
3import re
4
5email = input("Enter an email address: ")
6
7pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$"
8
9if re.match(pattern, email):
10 print("Valid email format")
11else:
12 print("Invalid email format")

Output

Enter an email address: user@example.com
Valid email format

What's going on

Toy pattern: local-part@domain.tld. user@example.com passes. a@b fails (no dot). a@b.c passes and is not a real mailbox. Do not ship this.

After this program

If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.