Open In App

Python – Extract domain name from Email address

Last Updated : 18 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Extracting the domain name from an email address involves isolating the part after the @ symbol. For example we are having string email= “[email protected]so we need to extract the domain name of email address so that the output becomes "example.com". To do this operation we can use methods like spilt(), partition(), Regular expression.

Using split()

split() method in Python divides a string into a list of substrings based on a specified delimiter.

Python
email = "[email protected]"

# Splitting the email string at the '@' symbol and accessing the second part (domain)
domain = email.split('@')[1]

print(domain) 

Output
example.com

Explanation:

  • split('@') function splits the string at the @ symbol.
  • Second part of the split string ([1]) is the domain name

Using Regular Expressions (re.search)

re.search() method in Python searches for a pattern within a string and returns the first match found.

Python
import re

# Defining an email string
e = "[email protected]"

# Using the search function to find a match for the domain part of the email
match = re.search(r'@([a-zA-Z0-9.-]+)', e)

# If a match is found, extracting the domain part (the part after '@') using the group() method
if match:
    domain = match.group(1)
   
    print(domain)

Output
example.com

Explanation:

  • Regular expression @([a-zA-Z0-9.-]+) matches the domain part after the @ symbol.
  • match.group(1) retrieves the matched domain.

Using partition()

partition() method splits the string into three parts: before the '@', the '@' symbol, and after the '@'. domain part is extracted by accessing third element using index.

Python
email = "[email protected]"

# Splitting the email at '@' and selecting the domain part
domain = email.partition('@')[2]
print(domain)

Output
example.com

Explanation:

  • partition('@') method splits the string into three parts: the part before the @, the @, and the part after.
  • Domain is the third part, accessed with [2].


Next Article
Practice Tags :

Similar Reads