How to Check if a String is Alphanumeric in Python
Uses the built-in str.isalnum() method to test whether a string contains only letters and numbers.
Python code
8 linesdef is_alphanumeric(s: str) -> bool:
return s.isalnum()
if __name__ == "__main__":
test_cases = ["Hello123", "Hello World", "12345", "", "Hello@World", "Python3"]
for case in test_cases:
result = is_alphanumeric(case)
print(f"{case!r:15} -> {result}")
Output
'Hello123' -> True
'Hello World' -> False
'12345' -> True
'' -> False
'Hello@World' -> False
'Python3' -> True
How it works
The str.isalnum() method returns True if every character in the string is alphanumeric (letters or digits) and the string is non-empty. It returns False for empty strings, because there are no characters to satisfy the condition. It also returns False if any character is a space, punctuation, or symbol. This method is locale-independent for ASCII letters, but properly handles Unicode letters as well.
Common mistakes
- Forgetting that empty strings return False
- Assuming spaces are allowed; they are not
- Confusing isalnum() with isalpha() or isdigit()
- Assuming it validates numeric values like floats (it only checks characters)
Variations
- Use a regex pattern like `re.fullmatch(r'[A-Za-z0-9]+', s)` for stricter ASCII-only checks
- Strip whitespace first with `s.strip().isalnum()` if spaces at edges should be ignored
Real-world use cases
- Validating usernames in a signup form to ensure only letters and numbers are allowed.
- Filtering log entries to find identifiers that contain only safe characters for indexing.
- Sanitizing input fields in an API before storing to avoid special character injection.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.