Python isalnum() Method

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Methods

What You’ll Learn

The isalnum() method returns True when every character in a string is a letter or digit and the string is not empty. It is a quick way to validate usernames, product codes, and other input that should contain only alphanumeric characters—no spaces, punctuation, or symbols.

01

Letters + Digits

Both are allowed.

02

Returns bool

True or False result.

03

No Arguments

Call directly on str.

04

Empty = False

Zero-length fails check.

05

Input Validation

Usernames and codes.

06

vs isalpha()

Know related methods.

Definition and Usage

In Python, isalnum() inspects each character in a string. If every character is a letter (az, AZ, or Unicode letters) or a digit (09) and the string has at least one character, it returns True. Otherwise it returns False. For example, "Hello123".isalnum() is True, but "Hello 123".isalnum() is False because of the space.

💡
Beginner Tip

isalnum() means “is alphanumeric”—letters or numbers, or a mix of both. It does not allow spaces, hyphens, underscores, or punctuation. For usernames with underscores, you need a custom check or regular expressions.

📝 Syntax

The isalnum() method takes no parameters:

python
string.isalnum()

Syntax Rules

  • string — any valid Python str object.
  • Return valueTrue if all characters are alphanumeric and the string is non-empty; otherwise False.
  • No arguments — passing arguments raises TypeError.
  • Read-only — the original string is never modified.
  • Unicode — letters from other languages (like é or ñ) count as letters in Python 3.

↩ Return Value

isalnum() always returns a boolean—never an integer or string. It returns True only when the string contains one or more characters and every character is a letter or digit. It returns False for empty strings, strings with spaces, and strings with any symbol or punctuation.

python
print("Hello123".isalnum())   # True
print("Hello 123".isalnum())  # False (space)
print("".isalnum())            # False (empty)
print("12345".isalnum())       # True (digits only)
print("Hello!".isalnum())      # False (punctuation)

⚡ Quick Reference

ExpressionResult
"Hello123".isalnum()True
"Hello 123".isalnum()False (space)
"".isalnum()False (empty)
"abc".isalnum()True (letters only)
"user_name".isalnum()False (underscore)
Basic
text.isalnum()

True or False

Validate
if username.isalnum():

Guard input

Strip first
text.strip().isalnum()

Ignore edge spaces

Compare
"abc".isalpha()

Letters only check

Examples Gallery

Run these examples in any Python 3 interpreter. Each one shows a common validation scenario.

📚 Getting Started

Check whether a string contains only letters and digits.

Example 1 — Basic isalnum()

A string with letters and numbers passes the check.

python
text = "Hello123"
result = text.isalnum()

print("Text:  ", text)
print("Result:", result)

How It Works

  • Every character in "Hello123" is a letter or digit.
  • The string is non-empty, so isalnum() returns True.
  • Mixing letters and numbers is perfectly valid for this method.

Example 2 — Space Makes It False

Even a single space causes isalnum() to return False.

python
text = "Hello 123"
result = text.isalnum()

print("Text:  ", repr(text))
print("Result:", result)

How It Works

The space between "Hello" and "123" is not alphanumeric. Spaces, tabs, and newlines all cause False.

📈 Practical Patterns

Edge cases, validation logic, and comparisons with related methods.

Example 3 — Empty String and Special Characters

See how isalnum() handles empty strings and punctuation.

python
samples = ["", "ABC", "123", "Hello!", "user_name"]

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

How It Works

  • Empty strings always return False.
  • Letters-only and digits-only strings both return True.
  • Punctuation (!) and underscores (_) are not alphanumeric.

Example 4 — Validating a Username

Use isalnum() in a simple input validation flow.

python
def is_valid_username(name):
    cleaned = name.strip()
    if not cleaned:
        return False, "Username cannot be empty."
    if not cleaned.isalnum():
        return False, "Use letters and numbers only."
    return True, "Username accepted."

for candidate in ["Mari123", "Mari 123", "Mari_123"]:
    ok, message = is_valid_username(candidate)
    print(candidate, "→", message)

How It Works

Call strip() first to ignore accidental leading or trailing spaces, then use isalnum() for the character check.

Example 5 — isalnum() vs isalpha() vs isdigit()

These three methods sound similar but test different rules.

python
text = "abc123"

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

print()
print("123".isalnum(), "123".isalpha(), "123".isdigit())
print("abc".isalnum(), "abc".isalpha(), "abc".isdigit())

How It Works

  • isalnum() accepts letters and digits together.
  • isalpha() requires all characters to be letters.
  • isdigit() requires all characters to be digits.

🚀 Common Use Cases

  • Username validation — reject names with spaces or special characters.
  • Product codes — verify SKU or serial numbers contain only letters and digits.
  • Form processing — quick check before saving user input to a database.
  • Password rules (partial) — as one step in a larger validation (note: symbols are often required in passwords).
  • Filtering data — skip or flag rows where a field is not alphanumeric.

🧠 How isalnum() Works

1

Python reads the string

You call isalnum() on a str object—literal or variable.

Input
2

Each character is checked

Python tests whether every character is a letter or digit. If the string is empty, the result is immediately False.

Scan
3

Boolean result is returned

True if all pass; False if any character fails or the string is empty.

Result
=

Validation complete

Use the boolean in conditionals to accept or reject input.

📝 Notes

  • Spaces, punctuation, underscores, and symbols all cause False.
  • An empty string "" always returns False—there must be at least one alphanumeric character.
  • Unicode letters (like é or ñ) count as letters in Python 3.
  • isalnum() does not check string length—combine it with len() for min/max rules.
  • Store the result in a variable if you need to use it multiple times on the same string.

Conclusion

The isalnum() method is a simple, readable way to check whether a string contains only letters and digits. It returns a clear boolean result, which makes it ideal for validating usernames, codes, and other user input in everyday Python programs.

Remember that spaces and symbols fail the check, empty strings return False, and related methods like isalpha() and isdigit() apply stricter single-type rules.

💡 Best Practices

✅ Do

  • Call strip() before validating user input
  • Combine with len() for minimum/maximum length rules
  • Use isalnum() for simple letter-and-digit checks
  • Pick isalpha() or isdigit() when you need one type only
  • Give clear error messages when validation fails

❌ Don’t

  • Expect underscores or hyphens to pass isalnum()
  • Use it as the only password security check
  • Assume an empty string returns True
  • Pass arguments to isalnum()
  • Rely on it for complex format rules—use regex when needed

Key Takeaways

Knowledge Unlocked

Five things to remember about isalnum()

Use these points when validating strings in Python.

5
Core concepts
🔢 02

True / False

Boolean return only.

Return
🛠 03

Zero Arguments

s.isalnum()

Syntax
👤 04

Validate Input

Usernames and codes.

Use case
05

Empty = False

No chars fails check.

Edge case

❓ Frequently Asked Questions

isalnum() returns True if every character in the string is a letter or digit and the string is not empty. It returns False if the string contains spaces, punctuation, symbols, or has no characters at all.
string.isalnum(). It takes no arguments and returns a boolean (True or False).
It returns False. An empty string has no alphanumeric characters, so isalnum() is always False for "".
No. A space is not a letter or digit, so "Hello 123".isalnum() returns False. Use strip() first if you need to ignore leading or trailing spaces.
isalnum() allows both letters and digits. isalpha() requires all characters to be letters only. isdigit() requires all characters to be digits only. For example, "abc123".isalnum() is True, but "abc123".isalpha() and "abc123".isdigit() are both False.
No. isalnum() only inspects the string and returns a boolean. The original string stays unchanged.

Explore More Python String Methods

Continue with isalpha(), isdigit(), and the rest of the string method reference.

Next: isalpha() →

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.

15 people found this page helpful