Python check if a string is alphanumeric

How to check if a string is alphanumeric in python:

If a string contains alphabet or numbers, then it is called alphanumeric. In python, it is easy to find out if a string is alphanumeric or not. Python string provides a method called isalnum that can be used to check that.

In this post, we will learn how to use use isalnum with examples.

Definition of isalnum:

isalnum is defined as below:


It returns one boolean value. It is True if all characters in the string are alphanumeric. Else, it returns False. For an empty string, it returns False.

Example of isalnum:

Let’s try isalnum with different strings:

str_arr = ['a', '', 'abc', 'abc123', '123', 'abc#$%', 'hello 123', 'hello123']

for item in str_arr:
    print('{} is : {}'.format(item, item.isalnum()))


  • str_arr is a list of strings and we are iterating through its items using a for-in loop.
  • Inside the loop, we are printing the string and the result of isalnum.

It will give the below output:

a is : True
 is : False
abc is : True
abc123 is : True
123 is : True
abc#$% is : False
hello 123 is : False
hello123 is : True

As you can see, even if the string contains a space, it is not considered a alphanumeric string. For example, hello 123 includes one space in the middle and it prints False for it.

python string alphanumeric check example

You might also like: