Python string isalnum() method with example

The isalnum() method in Python is a built-in method used for string handling. It returns True if all the characters in the string are alphanumeric (a-z, A-Z, 0-9) and there is at least one character, otherwise it returns False.


str = "Hello123"
print(str.isalnum()) # Output: True

String is the text in which you want to check if all characters are alphanumeric.

How to use the isalnum() method:

str = "Hello123"
print(str.isalnum()) # This will output: True

Example 1

Using isalnum() to confirm that a string consists only of alphanumeric characters.

str1 = "Hello123"
print(str1.isalnum()) # Output: True

str2 = "Hello 123" 
print(str2.isalnum()) # Output: False

Example 2

If you’re working with a list of strings and want to remove any strings that aren’t alphanumeric, isalnum() can be used.

data = ['Hello123', 'Hello 123', '$$$$$', '123', 'abc']
cleaned_data = [item for item in data if item.isalnum()]

print(cleaned_data) # Output: ['Hello123', '123', 'abc']