String method

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.

BeginnerEvery example below runs in your browser. Change the code and press Run.

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

Pythoneditable
print("user123".isalnum())
print("user_123".isalnum())
print("hello world".isalnum())
print("".isalnum())
Output
True
False
False
False

2Check a user name

Pythoneditable
for name in ["lena92", "omar.h", "yuki 7", "Ana"]:
    if name.isalnum():
        print(name, "- ok")
    else:
        print(name, "- only letters and digits, please")
Output
lena92 - ok
omar.h - only letters and digits, please
yuki 7 - only letters and digits, please
Ana - ok

3Allow underscores too

Pythoneditable
name = "user_123"
print(name.replace("_", "").isalnum())
Output
True

4Find the symbols in a password

Pythoneditable
password = "Pa$$w0rd!"
symbols = [c for c in password if not c.isalnum()]
print(symbols)
print("Has a symbol:", len(symbols) > 0)
Output
['$', '$', '!']
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().

Pythoneditable
code = ""
print(code.isalnum())
print(code == "" or code.isalnum())
Output
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().

Spotted a mistake on this page? Tell us