Extracting the domain name from an email address involves isolating the part after the @ symbol. For example we are having string email= "user@example.com" 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.
email = "user@example.com"
# 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.
import re
# Defining an email string
e = "user@example.com"
# 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.
email = "user@example.com"
# 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].