Skip to content

S1Q2 · Extract Email Username

⚡ Quick Reference

Function: extract_email_username(email: str) -> str

Core idea: split on @ and return the first part.

def extract_email_username(email: str) -> str:
    return email.split("@")[0]

Key rules: - Exactly one @ in the input -guaranteed - Everything before @ is the username - split("@")[0] is the simplest and most direct approach


Problem Statement

Problem

Write a function extract_email_username(email) that returns everything before the @ symbol in a valid email address string.

Examples:

Input
"ananya.sharma@iitd.ac.in"
Output
"ananya.sharma"
Input
"rahul123@gmail.com"
Output
"rahul123"
Input
"priya_r@company.in"
Output
"priya_r"

Understanding the problem

An email address has exactly one @ that separates the username from the domain. Everything to the left of @ is what we need:

"ananya.sharma@iitd.ac.in"
              "@" is the separator

Left:  "ananya.sharma"  ← return this
Right: "iitd.ac.in"    ← ignore

Solution approaches

def extract_email_username(email: str) -> str:
    return email.split("@")[0]

split("@") produces ["ananya.sharma", "iitd.ac.in"]. Index [0] gives the username. Clean and direct.

def extract_email_username(email: str) -> str:
    username, _, _ = email.partition("@")
    return username

str.partition(sep) splits into exactly three parts: (before, sep, after). Slightly more explicit than split -makes it clear you're splitting on the first occurrence of @ and taking the left part.

def extract_email_username(email: str) -> str:
    at_pos = email.index("@")
    return email[:at_pos]

str.index("@") finds the position of @. Slice up to that position. More verbose but shows the underlying mechanism clearly.

extract_email_username = lambda email: email.split("@")[0]

The entire function as a lambda -useful when passing as an argument to map().


Key takeaways

01

split(sep)[0] for "everything before"

s.split(sep)[0] is the standard pattern for extracting everything before a known separator. Works for @, :, ., or any delimiter.

02

str.partition() vs str.split()

partition() always returns exactly three parts and never creates extra splits. split() splits on every occurrence. For a guaranteed single separator like @, both work equally well.

03

str.index() vs str.find()

index() raises a ValueError if the separator isn't found. find() returns -1. Since @ is guaranteed present, index() is the safer choice -it fails loudly on bad input.