Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท String Methods

Python str.isalnum() method

Reference for Python str.isalnum(): test that a string is non-empty and made only of letters and digits, with Unicode, spaces and underscore pitfalls.

The str.isalnum() method returns True if the string is not empty and every character is alphanumeric, meaning a letter or a number. Spaces, punctuation, the underscore and symbols make it return False, and so does an empty string.

It is convenient for quick checks such as "is this a simple username or product code?", but remember that it accepts letters and digits from every script, not only A to Z and 0 to 9.

Python
print("abc123".isalnum())    # True
print("abc 123".isalnum())   # False

Try it

Python Letters and digits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Validating input, and Unicode

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
str.isalnum()
Name Description
(none) The method takes no arguments.

Return value: True if the string has at least one character and all characters satisfy isalpha(), isdecimal(), isdigit() or isnumeric(); otherwise False.

Raises: nothing.

Usage notes

  • Empty string is False. Test for emptiness separately when it matters.
  • Not limited to ASCII. Accented letters, Chinese characters and non-Latin digits count as alphanumeric. Combine with isascii() for a strict A to Z, 0 to 9 check, or use a regular expression such as [A-Za-z0-9]+.
  • Underscore and hyphen fail. "user_name".isalnum() is False. Identifiers are better tested with isidentifier().
  • The whole string must pass. A single space or punctuation mark makes the answer False. Check each word, or filter characters, if that is not what you want.
  • Numeric categories are broad. Characters such as superscripts or fractions count through isdigit() or isnumeric(), even though int() cannot convert them.
  • Not a security check. Allow-listing characters is a reasonable first filter, but validation rules for passwords and file names should be more specific.
  • Works per character, so "".join(ch for ch in s if ch.isalnum()) is the usual way to strip everything else.