What is string.isalnum in Python?

The isalnum method checks if all the characters of a string are alphanumeric. If the string contains only alphanumeric characters, then isalnum returns True; otherwise, it returns False.

Alphanumeric characters include:

  • Alphabets (a-z) (A-Z)
  • Numbers 0-9
  • Subscript, superscript
  • Fractions
  • Roman numerals

Syntax

string.isalnum()

Return value

  • The function returns True if all characters of the string are alphanumerical.

  • The function returns False if even one character of the string is not an alphanumeric character or if the string is empty.

Example 1

string = "123abc"
string.isalnum() #True

In the string above, 123abc, all the characters are alphanumeric, so the function returns True.

Example 2

string = "123 abc"
string.isalnum() #False

In the string above, 123 abc, the space is not an alphanumeric character, so isalnum() returns False.

Example 3

string = ""
string.isalnum() #False

The isalnum method returns False for an empty string.

Example 4

string = "½"
string.isalnum() #True

isalnum returns True for the ½ string because fractions are considered alphanumeric characters.

Code

string = "123abc"
print(string, " isalnum --> ", string.isalnum())
string = "123 abc"
print(string, " isalnum --> ", string.isalnum())
string = ""
print(string, "isalnum -->", string.isalnum())
string = "½"
print(string, "isalnum -->", string.isalnum())

Free Resources