How to Check if a String is Alphanumeric in Python

Uses the built-in str.isalnum() method to test whether a string contains only letters and numbers.

Easy Python 3.9+ Aug 9, 2026 Strings & text 14 views 0 copies

Python code

8 lines
Python 3.9+
def is_alphanumeric(s: str) -> bool:
    return s.isalnum()

if __name__ == "__main__":
    test_cases = ["Hello123", "Hello World", "12345", "", "Hello@World", "Python3"]
    for case in test_cases:
        result = is_alphanumeric(case)
        print(f"{case!r:15} -> {result}")

Output

stdout
'Hello123'      -> True
'Hello World'   -> False
'12345'         -> True
''              -> False
'Hello@World'   -> False
'Python3'       -> True

How it works

The str.isalnum() method returns True if every character in the string is alphanumeric (letters or digits) and the string is non-empty. It returns False for empty strings, because there are no characters to satisfy the condition. It also returns False if any character is a space, punctuation, or symbol. This method is locale-independent for ASCII letters, but properly handles Unicode letters as well.

Common mistakes

  • Forgetting that empty strings return False
  • Assuming spaces are allowed; they are not
  • Confusing isalnum() with isalpha() or isdigit()
  • Assuming it validates numeric values like floats (it only checks characters)

Variations

  1. Use a regex pattern like `re.fullmatch(r'[A-Za-z0-9]+', s)` for stricter ASCII-only checks
  2. Strip whitespace first with `s.strip().isalnum()` if spaces at edges should be ignored

Real-world use cases

  • Validating usernames in a signup form to ensure only letters and numbers are allowed.
  • Filtering log entries to find identifiers that contain only safe characters for indexing.
  • Sanitizing input fields in an API before storing to avoid special character injection.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.