How to check if given string contains only alphanumeric characters in Python?

Python String – Check if string is 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

Examples

1. Given string with only alphanumeric characters

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

Python Program

str = 'pythonexamples125'

if str.isalnum():
    print('Given string contains only alphanumeric.')
else:
    print('Given string does not contain only alphanumeric.')
Run Code Copy

Output

Given string contains only alphanumeric.

The function returns boolean value True, since the string contains only alphabets and numbers.

2. Given string with alphanumeric characters and spaces

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

Python Program

str = 'Python Examples 125'

if str.isalnum():
    print('Given string contains only alphanumeric.')
else:
    print('Given string does not contain only alphanumeric.')
Run Code Copy

Output

Given string does not contain only alphanumeric.

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

3. Given 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.

Python Program

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

if str.isalnum():
    print('Given string contains only alphanumeric.')
else:
    print('Given string does not contain only alphanumeric.')
Run Code Copy

Output

Given string does not contain only alphanumeric.

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

Summary

In summary, to determine if a given string is alphanumeric, use String.isalnum() function.

Related Tutorials

Code copied to clipboard successfully 👍