Contents
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
Example 1: 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'
isalnum = str.isalnum()
print('Is String Alphanumeric :', isalnum)
Run Output
Is String Alphanumeric : True
The function returns boolean value True
, since the string contains only alphabets and numbers.
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.
Python Program
str = 'Python Examples 125'
isalnum = str.isalnum()
print('Is String Alphanumeric :', isalnum)
Run Output
Is String Alphanumeric : False
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.
Python Program
str = "Python Examples $125 @6 O'Clock"
isalnum = str.isalnum()
print('Is String Alphanumeric :', isalnum)
Run Output
Is String Alphanumeric : False
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.