Python String isalnum()

Python String isalnum() method

Python String isalnum() method is used to check if all characters in the string are alphanumeric(alphabets and numeric) characters and there is at least one character in the string.

Consider that given string is in x.

x = "Abc123456"

Then the return value of x.isalnum() is

True

In this tutorial, you will learn the syntax and usage of String isalnum() method in Python language.

Syntax of isalnum() method

The syntax of String isalnum() method in Python is given below.

str.isalnum()

Parameters

The string isalnum() method takes no parameters.

Return value

The string isalnum() method returns a boolean value of True if all characters in the string are alphabets and/or numeric characters and there is at least one character in the string, otherwise False.

Examples

1. Checking if given string is alphanumeric in Python

In this example, we take a string value in variable x. We have to check if all characters in the string are alphanumeric.

Call isalnum() method on the string object x and use the returned value as a condition in Python if else statement as shown in the following program.

Since all characters in the string are digits (numeric) and alphabets, isalnum() method returns True, and the if-block executes.

Python Program

x = "Abc123456"

if x.isalnum():
    print('Given string is ALPHA-NUMERIC.')
else:
    print('Given string is NOT ALPHA-NUMERIC.')
Run Code Copy

Output

Given string is ALPHA-NUMERIC.

2. Checking if string with special characters is alphanumeric in Python

In the following program, we take a string value in variable x such that some of the characters in the string are special symbols(non alphanumeric), for example @ symbol.

Since, not all characters in the string are alphanumeric, isalnum() method returns False, and the else-block executes.

Python Program

x = "Abc@123"

if x.isalnum():
    print('Given string is ALPHA-NUMERIC.')
else:
    print('Given string is NOT ALPHA-NUMERIC.')
Run Code Copy

Output

Given string is NOT ALPHA-NUMERIC.

3. Checking if an empty string is alphanumeric in Python

In the following program, we take an empty string value in variable x, and check if this empty string is alphanumeric.

Since, there is not at least one character in the string, isalnum() method returns False, and the else-block executes.

Python Program

x = "Abc@123"

if x.isalnum():
    print('Given string is ALPHA-NUMERIC.')
else:
    print('Given string is NOT ALPHA-NUMERIC.')
Run Code Copy

Output

Given string is NOT ALPHA-NUMERIC.

Summary

In this tutorial of Python String Methods, we learned about String isalnum() method, its syntax, and examples.

Related Tutorials

Code copied to clipboard successfully 👍