Write a Python function to check if a string is a valid email address.
Posted by CarolTh
Last Updated: August 24, 2024
Validating Email Addresses in Python
Validating email addresses is a common requirement when developing applications that involve user registration or communication. A well-formed email address typically follows the format local-part@domain. Python provides various methods for achieving this validation, including regular expressions. Here is a Python function that checks if a string is a valid email address using the re module, which allows for powerful pattern matching.
import re

def is_valid_email(email):
    """
    Check if the given email address is valid.

    Parameters:
    email (str): The email address to check.

    Returns:
    bool: True if valid, False otherwise.
    """
    # Define the regular expression for validating an email
    email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    
    # Use re.match to check if the email matches the regular expression
    if re.match(email_regex, email):
        return True
    else:
        return False

# Example usage
if name == "main":
    test_emails = [
        "example@mail.com",
        "user.name+tag@domain.co",
        "user@-domain.com",
        "user@domain..com",
        "user@domain.com.au",
        "invalid-email@.com"
    ]

    for email in test_emails:
        print(f"{email}: {is_valid_email(email)}")
Explanation of the Code
- Regular Expression: The pattern ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ is used to match valid email formats: - ^[a-zA-Z0-9._%+-]+ matches the local part (before the @ symbol), allowing letters, numbers, and certain symbols. - @[a-zA-Z0-9.-]+ ensures that there is a domain specified, including subdomains. - \.[a-zA-Z]{2,}$ requires a top-level domain with at least two characters. - Function Logic: The is_valid_email function uses re.match to check if the provided string fits the defined pattern. It returns True if valid and False otherwise.
Considerations
- This function checks for a basic format of email addresses but does not verify the existence of the domain or the specific email. Such checks require more complex validation logic and possibly network calls. - The regular expression can be adjusted depending on additional specific requirements for email formats. - Keep in mind the evolving standards for valid email formats, as some conditions may change over time.