How to Check if given String contains only Alphanumeric Characters in Python?

Python String – Check if Alphanumeric – isalnum()

To check if given string contains only alphanumeric characters in Python, use String.isalnum() function.

The function returns True if the string contains only alphanumeric characters and False if not.

Following are the allowed Alphanumeric Characters.

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
Run

Example 1: String with only Alphanumeric Characters

In this example, we take a String with only alphanumeric characters. We will apply isalnum() function.

str = 'pythonexamples125'

isalnum = str.isalnum()

print('Is String Alphanumeric :', isalnum)
Run

Output

Is String Alphanumeric : True
Run

The function returns the boolean value True.

Example 2: String with Alphanumeric Characters and Spaces

In this example, we take a String with only alphanumeric characters and spaces. We will apply isalnum() function.

str = 'Python Examples 125'

isalnum = str.isalnum()

print('Is String Alphanumeric :', isalnum)
Run

Output

Is String Alphanumeric : False
Run

The function returns the boolean value False since the string contains spaces which are not alphanumeric.

Example 3: String with Alphanumeric Characters and Special Characters

In this example, we take a String with only alphanumeric characters and special characters. We will apply isalnum() function to the String.

str = "Python Examples $125 @6 O'Clock"

isalnum = str.isalnum()

print('Is String Alphanumeric :', isalnum)
Run

Output

Is String Alphanumeric : False
Run

The function returns the boolean value False since the string contains special characters which are not alphanumeric.