str.isalnum()
Returns True when a string is not empty and every character is a letter or a number. Spaces and symbols make it False.
str.isalnum()isalnum() ("is alphanumeric") returns True when the string has at least one character and every character is a letter or a number. It is str.isalpha() and str.isnumeric() combined, character by character.
It is handy for simple checks of user names, codes and passwords' character types.
The underscore _, the hyphen, spaces and dots are not letters or numbers, so "user_1" gives False. And because it uses the wide numeric rule, characters like "²" and "½" count.
Return value
True or False.
Examples
1Simple checks
print("user123".isalnum())
print("user_123".isalnum())
print("hello world".isalnum())
print("".isalnum())True False False False
2Check a user name
for name in ["lena92", "omar.h", "yuki 7", "Ana"]:
if name.isalnum():
print(name, "- ok")
else:
print(name, "- only letters and digits, please")lena92 - ok omar.h - only letters and digits, please yuki 7 - only letters and digits, please Ana - ok
3Allow underscores too
name = "user_123"
print(name.replace("_", "").isalnum())True
4Find the symbols in a password
password = "Pa$$w0rd!"
symbols = [c for c in password if not c.isalnum()]
print(symbols)
print("Has a symbol:", len(symbols) > 0)['$', '$', '!'] Has a symbol: True
Common mistakes
Forgetting that an empty string is False
If a field may be empty, decide what that should mean before relying on isalnum().
code = ""
print(code.isalnum())
print(code == "" or code.isalnum())False True
Questions people ask
Does isalnum() accept the underscore?
No. Replace it first (s.replace("_", "")) or use the re module with \w.
Does isalnum() accept accented letters?
Yes, letters from every alphabet count.
How do I check for ASCII letters and digits only?
text.isascii() and text.isalnum().