Python - Check If All the Characters in a String Are Alphanumeric?


To check if all the characters in a string are alphanumeric, we can use the isalnum() method in Python and Regex also. First, let us understand what is alphanumeric.

What is Alphanumeric?

Alphanumeric includes both letters and numbers i.e., alphabet letter (a-z) and numbers (0-9). Examples: A, a, k, K, 8, 10, 20, etc.

Let us see an example of an Alphanumeric string

8k9q2i3u4t

Let us see an example of a string wherein all the characters aren’t Alphanumeric -

$$###k9q2i3u4t

Check If All the Characters in a String Are Alphanumeric using isalnum()

We will use the built-in isalnum() method to check if all the characters are alphanumeric -

# String1 mystr1 = "8k9q2i3u4t" # Display the string2 print("String = ",mystr1); # Check string1 for alphanumeric print("Is String1 alphanumeric = ",mystr1.isalnum()) # String2 mystr2 = "##$$9hnkh67" # Display the string2 print("\nString2 = ",mystr2); # Check string2 for alphanumeric print("Is String2 alphanumeric = ",mystr2.isalnum())

Output

String =  8k9q2i3u4t
Is String1 alphanumeric =  True

String2 =  ##$$9hnkh67
Is String2 alphanumeric =  False

Check If All the Characters in a String Are Alphanumeric using Regex

For using Regex in Python, you need to install the re module. To install, use pip

pip install re

To use the re module, import it:

import re

Let us now see an example

import re # String1 mystr1 = "m4w5r6" # Display the string2 print("String = ",mystr1); # Check string1 for alphanumeric print("Is String1 alphanumeic = ",bool(re.match('^[a-zA-Z0-9]+$', mystr1))) # String2 mystr2 = "pn#$nk2h1" # Display the string2 print("\nString2 = ",mystr2); # Check string2 for alphanumeric print("Is String2 alphanumeic = ",bool(re.match('^[a-zA-Z0-9]+$', mystr2)))

Output

String =  m4w5r6
Is String1 alphanumeic =  True

String2 =  pn#$nk2h1
Is String2 alphanumeic =  False

Updated on: 15-Sep-2022

413 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements