Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Sanitize a username input

Create a sanitizer for raw username strings that enforces safe characters, casing, and length limits. Return None for invalid results.

Python practice15 minError Handling & Edge CasesIntermediateLast updated March 20, 2026

Problem statement

User-entered usernames can contain whitespace, punctuation, mixed casing, or other unwanted characters. Implement sanitize_username(name) to: - Accept a value and attempt to coerce it to a string. - Trim leading/trailing whitespace and lowercase the name. - Replace internal whitespace sequences with a single underscore. - Remove characters other than lowercase letters, digits, underscore (_), and hyphen (-). - Collapse multiple underscores into a single underscore. - Enforce a minimum length of 3 characters. If the cleaned name is shorter than 3, return None. - Enforce a maximum length of 20 characters by truncating the cleaned name to 20 characters. - If the cleaned username does not start with a lowercase letter (a-z), return None. Return the sanitized username string or None when it is invalid.

Task

Implement sanitize_username(name) that returns a cleaned username or None when the input can't be turned into a valid username.

Examples

Basic sanitization

Input

sanitize_username(' Bob Smith ')

Output

bob_smith

Trims spaces, lowercases, replaces internal spaces with underscore, removes invalid characters.

Input format

Single value (typically a string) representing a username.

Output format

A sanitized username string or None (represented as empty output by the test harness) if invalid.

Constraints

Only use the Python standard library. Be defensive: handle non-string inputs by converting to str where sensible, but still apply validation rules.

Samples

Sample 1

Input

sanitize_username('User!@#')

Output

user

Punctuation removed, case lowered.