Sitemap

Email Slicing with Python

Based on user email id extract user name & domain name

1 min readOct 24, 2023

Problem Statement: Based on user email id extract user name & domain name. As example: 17vidushigupta@gmail.com would have following segmentation

user name: 17vidushigupta

domain name: gmail.com

Solution Approach: There are few ways this can be done. As a programmer it is important to make sure the data received or input received would not fail the program for expected outputs. If it is confirmed that data is already syntactically correct, has no ambiguity and already follows the email specifications for each value, then the simple approach of string splitting would suffice.

user_input_1 = input("Enter the email: ")
email_info = user_input_1.split("@")
print(f"The user name is '{email_info[0]}' & domain name is '{email_info[1]}'\n")

However, in real world not always the data is synthesized & may have corner cases where we need to confirm the accuracy of the format, in such scenarios before extracting or dividing the input, it is advisable to verify the format. Regex module is a powerful package which when used correctly would eliminate the need of several if-else statements & can concisely validate the several variations of input.

import re
user_input = input("Enter the email for regex example: ")
email_info = re.findall("^([a-zA-Z0-9]+)@([a-zA-Z]+\.[a-zA-Z]+)", user_input)

if(email_info): # if the regex expression matched & returned the value
print(f"The user name is '{email_info[0][0]}' & domain name is '{email_info[0][1]}'")
else:
print("Provide correct email address") # indicates list is retured empty while regex method tried to match the value

For executable file & syntax details, follow the git link

--

--

No responses yet