Python isalnum() Method

Definition
In Python, isalnum() returns True when every character is a letter or digit and the string is not empty.
It takes no arguments. Spaces, punctuation, and symbols make it return False.
Syntax
Call isalnum on the string. Start with this line.
| Call | What it does |
|---|
"abc123".isalnum() | Returns True. |
"Hello!".isalnum() | Returns False (punctuation). |
An empty string always returns False.
Library declarations
Parameters
This method has no parameters.
Return Value
| Return Value | Description |
|---|
| bool | True if all characters are letters or digits. |
Python Examples
Example 1 — Basic isalnum() Checks
See what passes and what fails.
samples = ["abc123", "Hello!", "a b", "", "Python"]
for s in samples:
print(repr(s), "→", s.isalnum())
'abc123' → True
'Hello!' → False
'a b' → False
'' → False
'Python' → True
How It Works
- Letters + digits pass.
"abc123" is fully alphanumeric. - Punctuation fails. The
! in "Hello!" breaks the rule. - Spaces fail. Even one space returns
False. - Empty fails.
"" is never alphanumeric.
Example 2 — Validate a Username Token
Allow only letters and digits after trimming outer spaces.
def is_valid_token(text):
cleaned = text.strip()
return cleaned != "" and cleaned.isalnum()
print(is_valid_token(" User42 "))
print(is_valid_token("User_42"))
print(is_valid_token(" "))
How It Works
- Strip edges. Outer spaces are removed before the test.
- Require content. All-space input becomes
"" → reject. - isalnum decides.
"User42" passes; underscore fails. - Keep rules clear. For underscores/dashes, use a custom check instead.
Example 3 — isalnum vs isalpha vs isdigit
Same string, three different questions.
s = "abc123"
print("isalnum:", s.isalnum())
print("isalpha:", s.isalpha())
print("isdigit:", s.isdigit())
isalnum: True
isalpha: False
isdigit: False
How It Works
- isalnum allows both. Letters and digits together →
True. - isalpha rejects digits. Needs letters only.
- isdigit rejects letters. Needs digits only.
- Pick the strictness you need. Mixed IDs →
isalnum.
Frequently Asked Questions
It returns True if every character is a letter or digit and the string is not empty.
False.
No. Any space makes it False.
isalnum() allows letters and digits. isalpha() is letters only. isdigit() is digits only.
Yes. Many non-ASCII letters can return True.
About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
9 people found this page helpful