Skip to content
Related Articles

Related Articles

Python – Extract domain name from Email address

View Discussion
Improve Article
Save Article
  • Last Updated : 24 Aug, 2022
View Discussion
Improve Article
Save Article

Given a String Email address, extract the domain name.

Input : test_str = ‘manjeet@geeks.com’ 

Output : geeks.com 

Explanation : Domain name, geeks.com extracted. 

Input : test_str = ‘manjeet@gfg.com’ 

Output : gfg.com 

Explanation : Domain name, gfg.com extracted.

Method #1 : Using index() + slicing

In this, we harness the fact that “@” symbol is separator for domain name and local-part of Email address, so, index() is used to get its index, and is then sliced till end.

Python3




# Python3 code to demonstrate working of
# Extract domain name from Email address
# Using index() + slicing
 
# initializing strings
test_str = 'manjeet@geeksforgeeks.com'
 
# printing original string
print("The original string is : " + str(test_str))
 
# slicing domain name using slicing
res = test_str[test_str.index('@') + 1 : ]
 
# printing result
print("The extracted domain name : " + str(res))

Output

The original string is : manjeet@geeksforgeeks.com
The extracted domain name : geeksforgeeks.com

Time Complexity: O(n) -> (slicing)

Auxiliary Space: O(n)

Method #2 : Using split()

In this, we split the string on “@” and use its 1st index to get the required domain name.

Python3




# Python3 code to demonstrate working of
# Extract domain name from Email address
# Using split()
 
# initializing strings
test_str = 'manjeet@geeksforgeeks.com'
 
# printing original string
print("The original string is : " + str(test_str))
 
# using split() to get domain name
res = test_str.split('@')[1]
 
# printing result
print("The extracted domain name : " + str(res))

Output

The original string is : manjeet@geeksforgeeks.com
The extracted domain name : geeksforgeeks.com

Time Complexity: O(n) -> (split)

Auxiliary Space: O(n)

Method #3 : Using find() and slicing

Python3




# Python3 code to demonstrate working of
# Extract domain name from Email address
 
# initializing strings
test_str = 'manjeet@geeksforgeeks.com'
 
# printing original string
print("The original string is : " + str(test_str))
 
res=test_str[test_str.find('@')+1:]
 
# printing result
print("The extracted domain name : " + str(res))

Output

The original string is : manjeet@geeksforgeeks.com
The extracted domain name : geeksforgeeks.com

Time Complexity: O(n) -> (find function)

Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!