S1Q2 · Extract Email Username¶
⚡ Quick Reference
Function: extract_email_username(email: str) -> str
Core idea: split on @ and return the first part.
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:
"ananya.sharma@iitd.ac.in"
"ananya.sharma"
"rahul123@gmail.com"
"rahul123"
"priya_r@company.in"
"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¶
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.
str.index("@") finds the position of @. Slice up to that position. More verbose but shows the underlying mechanism clearly.
Key takeaways¶
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.
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.
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.