Python isalnum() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
String

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.

python
ok = text.isalnum()
CallWhat it does
"abc123".isalnum()Returns True.
"Hello!".isalnum()Returns False (punctuation).

An empty string always returns False.

Library declarations
python
str.isalnum() → bool

Parameters

This method has no parameters.

Return Value

Return ValueDescription
boolTrue if all characters are letters or digits.

Python Examples

Example 1 — Basic isalnum() Checks

See what passes and what fails.

python
samples = ["abc123", "Hello!", "a b", "", "Python"]

for s in samples:
    print(repr(s), "→", s.isalnum())

How It Works

  1. Letters + digits pass. "abc123" is fully alphanumeric.
  2. Punctuation fails. The ! in "Hello!" breaks the rule.
  3. Spaces fail. Even one space returns False.
  4. Empty fails. "" is never alphanumeric.

Example 2 — Validate a Username Token

Allow only letters and digits after trimming outer spaces.

python
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

  1. Strip edges. Outer spaces are removed before the test.
  2. Require content. All-space input becomes "" → reject.
  3. isalnum decides. "User42" passes; underscore fails.
  4. Keep rules clear. For underscores/dashes, use a custom check instead.

Example 3 — isalnum vs isalpha vs isdigit

Same string, three different questions.

python
s = "abc123"

print("isalnum:", s.isalnum())
print("isalpha:", s.isalpha())
print("isdigit:", s.isdigit())

How It Works

  1. isalnum allows both. Letters and digits together → True.
  2. isalpha rejects digits. Needs letters only.
  3. isdigit rejects letters. Needs digits only.
  4. 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.

Next: isalpha()

Check whether every character is a letter.

isalpha() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

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