Tuesday, August 17, 2021

Email Slicer in Python


 

We will slice the email address and get the username and domain using three different methods: 

1) The conventional method of slicing

2) Using split function

3) Regex(Regular Library) Library 

So, let's start looking at each method in detail with the code.

1) Slicing

 First of all we will ask for the email-address. Then we will write two expressions to slice the email address each for username and domain.

 
 email=input("Enter email address : ")

username=email[:email.index('@')]
domain=email[email.index('@')+1:]

print("\nUsername : "+ username + "\nDomain name : "+ domain)
 

Finally we will print the username and domain.

2) Using Split function

Here we will input the email-address. Then we will split the email address from '@' using just one statement. i.e. email.split('@'). It will split the string from '@' and return list. Then we will print the list

 
 email=input("Enter email address : ")

l1=email.split('@')

print(f"\n\nUsername : {l1[0]} \nDomain name : {l1[1]}")
 

3)Using Regex

Here, we will first import the re module. Then we will ask for the user input (Email address to be sliced).

import re
email=input("Enter email address : ")

 Then we will write a regular expression which will split our string from  '@'. We can also split from more than one element by just adding more elements with a space with @. The print(result) will print a sliced list because the regex expression will return a list which is been splitted by '@'

result=re.split('[@]',email)
print(result)

 For example if I want my email address to split from '.' and '#' too, then I will write the expression as follows,

result=re.split('[@ . #]',email)

Then we will print the list which was splitted, here specifically we will print using the f string. Although we can use any method to print.  Below is the complete code for the Email Slicer using regex library

 
import re
email=input("Enter email address : ")

result=re.split('[@ .]',email)
print(result)

print(f"\n\nUsername is {result[0]} \nDomain name {result[1]}")
 

 

 

No comments:

Post a Comment

Time

  A brief look at time......  

Popular Posts