Write a function that validates a username against a common set of rules.
validate_username(s)
Valid usernames: are between 3 and 16 characters long (inclusive), start with a letter, and contain only letters, digits, or underscores after that first character.
validate_username("ada99") // → True (5 chars, starts with a letter)
validate_username("9ada") // → False (starts with a digit)
validate_username("ab") // → False (only 2 characters -- too short)
validate_username("valid_user_1") // → True (12 chars)
import re
def validate_username(s):
return re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{2,15}", s) is not None
The pattern is built from two pieces glued together, matching the two different rules for "first character" versus "the rest":
[A-Za-z] — exactly one letter (upper or lowercase), matching the "must start with a letter" rule. No digits or underscores are allowed in this character class, so a username starting with a digit (like "9ada") simply won't match here at all.[A-Za-z0-9_]{2,15} — between 2 and 15 more characters, each a letter, digit, or underscore.The {2,15} is the detail worth double-checking: since the first character is already accounted for by the first part of the pattern, the total length is 1 + (2 to 15), which works out to 3 to 16 characters overall — exactly matching the "3 to 16 characters" requirement from the spec. It's a common mistake to write {3,16} here directly, forgetting that the first character was already consumed by the earlier part of the pattern, which would incorrectly require 4-to-17 total characters.
re.fullmatch (not re.search) ensures the entire string has to fit this shape — a string like "ab" (only 2 characters total) fails because there's no way to have 1 letter plus at least 2 more characters within just 2 characters total.
import re
def validate_username(s):
return re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{2,15}", s) is not None
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.