Skip to main content

How to check if a string is alphanumeric in Python

How to check if a string is alphanumeric in Python.

Here is a step-by-step tutorial on how to check if a string is alphanumeric in Python:

Step 1: Start by defining a function called is_alphanumeric that takes a string as an input parameter.

Step 2: Inside the function, use the isalnum() method to check if the string contains only alphanumeric characters. The isalnum() method returns True if all characters in the string are alphanumeric (letters or numbers), and False otherwise.

Step 3: Return the result of the isalnum() method as the output of the function.

Here is an example code snippet that implements the above steps:

def is_alphanumeric(string):
return string.isalnum()

You can now use the is_alphanumeric() function to check if a string is alphanumeric. Here are a few examples:

print(is_alphanumeric("Hello123"))  # Output: True
print(is_alphanumeric("Hello!")) # Output: False
print(is_alphanumeric("12345")) # Output: True
print(is_alphanumeric("")) # Output: False

In the first example, the string "Hello123" contains only alphanumeric characters, so the output is True. In the second example, the string "Hello!" contains a non-alphanumeric character (!), so the output is False. In the third example, the string "12345" consists of only numeric characters, so the output is True. Finally, an empty string is considered non-alphanumeric, so the output is False.

You can customize the is_alphanumeric() function further based on your specific requirements. For example, if you want to ignore whitespace characters, you can use the replace() method to remove them before checking for alphanumeric characters:

def is_alphanumeric(string):
string = string.replace(" ", "")
return string.isalnum()

This modified version of the function removes any whitespace characters from the input string before performing the alphanumeric check.