Validate text with character tests
isdigit(), isalpha() and isalnum() answer whether every character of a text is a digit, a letter, or either. Combined with length and position checks, they validate codes, usernames and numbers before the program trusts them.
- Use
isdigit,isalphaandisalnum, and know they are False for an empty text - Combine length, position and character checks into one validation function
- Collect every rule a text breaks, not just the first
Text typed into a form can't be trusted until it's checked: a ZIP code must be five digits before int sees it, and a username must contain only allowed characters before it's stored. Three methods test what a text is made of:
text.isdigit(): every character is a digit (0–9).text.isalpha(): every character is a letter.text.isalnum(): every character is a letter or a digit.
All three are False for an empty text, and they say nothing about length or position: combine them with len and indexing.
Run each example to see what it prints. Running examples doesn't count toward progress.
for text in ["77002", "7700a", "", "-5", "3.5", "Nora", "Nora Garcia", "HOM22847"]: print("[" + text + "]", text.isdigit(), text.isalpha(), text.isalnum())
Real validation is several rules. Check the cheap structural ones first (length, a separator at a fixed position), then the characters of each part. A function that returns a list of every problem lets a form show all its errors at once instead of one per attempt.
def password_problems(password): """Return a list of every rule the password breaks.""" problems = [] if len(password) < 10: problems.append("at least 10 characters") has_digit = False has_letter = False has_symbol = False for ch in password: if ch.isdigit(): has_digit = True elif ch.isalpha(): has_letter = True elif ch != " ": has_symbol = True if not has_digit: problems.append("a digit") if not has_letter: problems.append("a letter") if not has_symbol: problems.append("a symbol") return problems print(password_problems("harbor")) print(password_problems("night-harbor-2024")) print(password_problems("12345678901"))
When to use it: before converting or storing anything typed by a person or read from a file. Mistakes to avoid:
- Expecting
isdigitto accept negative or decimal numbers. - Forgetting that an empty text fails every test, which is usually what you want, but check it deliberately.
- Validating after converting:
int("7a")raises ValueError before your check runs. - Forgetting to
stripfirst when spaces at the ends are allowed.
isdigit,isalphaandisalnumtest every character, and are False for empty text.- Validate structure first (length, fixed positions), then characters, then convert.
- Return every problem so a form can show them all.
- Next module: collection algorithms: filter, transform, group, join and de-duplicate records.