Python str.isalnum() function


In Python, the str.isalnum() method is used to check if all characters in a string are alphanumeric, meaning that they are either letters (a-z, A-Z) or digits (0-9). This method returns True if the string contains at least one character and all characters are alphanumeric; otherwise, it returns False.

Syntax

str.isalnum()

Example Usage

  1. Basic usage with letters and digits:
text = "Hello123" result = text.isalnum() print(result) # Output: True
  1. Including spaces:
text = "Hello 123" result = text.isalnum() print(result) # Output: False (space is not alphanumeric)
  1. With special characters:
text = "Hello@123" result = text.isalnum() print(result) # Output: False (the '@' is not alphanumeric)
  1. Checking an empty string:
text = "" result = text.isalnum() print(result) # Output: False (empty string has no characters)
  1. Using non-English alphanumeric characters:
text = "Café123" result = text.isalnum() print(result) # Output: True (accented 'é' is considered a letter)
  1. Only letters:
text = "HelloWorld" result = text.isalnum() print(result) # Output: True (all letters)
  1. Only digits:
text = "12345" result = text.isalnum() print(result) # Output: True (all digits)

Important Notes

  • The isalnum() method will return False if the string contains any characters that are not letters or digits, including whitespace and punctuation.
  • It considers Unicode characters as well, so letters from various languages and scripts are included as valid alphanumeric characters.

Summary

  • Use str.isalnum() to check if a string consists entirely of alphanumeric characters.
  • It returns True for strings made up of letters and digits (including accented characters) and False for strings that contain any non-alphanumeric characters.