Last modified: Feb 23, 2026 By Alexander Williams

Check Alphanumeric Characters in Python

Working with text is common in programming. You often need to validate user input. A frequent task is checking if a character is alphanumeric.

An alphanumeric character is a letter or a number. This includes A-Z, a-z, and 0-9. It excludes spaces, punctuation, and symbols.

Python makes this check very simple. It provides a built-in string method. This guide will show you how to use it effectively.

What is an Alphanumeric Character?

Let's define our terms clearly. Alphanumeric means a character is either a letter or a digit.

Letters include all uppercase (A-Z) and lowercase (a-z) characters. Digits are the numbers 0 through 9. Anything else is not alphanumeric.

For example, 'a', 'Z', and '5' are alphanumeric. Characters like '@', ' ', and '!' are not. This is crucial for data cleaning and validation.

The Python isalnum() Method

Python's string class has a method called isalnum(). It returns True if all characters in the string are alphanumeric.

It returns False if at least one character is not alphanumeric. An empty string also returns False.

The method does not take any arguments. Its syntax is straightforward: string.isalnum().

Basic Usage of isalnum()

Here is a simple example. We check different strings.


# Example 1: Basic checks with isalnum()
test_string1 = "Hello123"
test_string2 = "Hello World!"
test_string3 = "12345"
test_string4 = ""
test_string5 = "Python3.9"

print(f"'{test_string1}' is alphanumeric: {test_string1.isalnum()}")
print(f"'{test_string2}' is alphanumeric: {test_string2.isalnum()}")
print(f"'{test_string3}' is alphanumeric: {test_string3.isalnum()}")
print(f"'{test_string4}' is alphanumeric: {test_string4.isalnum()}")
print(f"'{test_string5}' is alphanumeric: {test_string5.isalnum()}")

'Hello123' is alphanumeric: True
'Hello World!' is alphanumeric: False
'12345' is alphanumeric: True
'' is alphanumeric: False
'Python3.9' is alphanumeric: False

The period in "Python3.9" makes it non-alphanumeric. The space in "Hello World!" also causes a False result.

Checking a Single Character

You might want to check just one character. The isalnum() method works on single-character strings too.

This is useful when iterating through a string. You can examine each character individually.


# Example 2: Checking individual characters
char1 = 'A'
char2 = '7'
char3 = '$'
char4 = ' '

print(f"'{char1}' is alphanumeric: {char1.isalnum()}")
print(f"'{char2}' is alphanumeric: {char2.isalnum()}")
print(f"'{char3}' is alphanumeric: {char3.isalnum()}")
print(f"'{char4}' is alphanumeric: {char4.isalnum()}")

'A' is alphanumeric: True
'7' is alphanumeric: True
'$' is alphanumeric: False
' ' is alphanumeric: False

Practical Application: Input Validation

A common use is validating usernames or passwords. Many systems require them to be alphanumeric.

Here is a function that validates a username. It uses the isalnum() method.


# Example 3: Username validation function
def validate_username(username):
    """
    Validates if a username is alphanumeric.
    Returns True if valid, False otherwise.
    """
    if not username:  # Check for empty string
        print("Username cannot be empty.")
        return False
    if username.isalnum():
        print(f"Username '{username}' is valid.")
        return True
    else:
        print(f"Username '{username}' is invalid. Use only letters and numbers.")
        return False

# Test the function
validate_username("User123")
validate_username("Best_User")
validate_username("2024User")
validate_username("")

Username 'User123' is valid.
Username 'Best_User' is invalid. Use only letters and numbers.
Username '2024User' is valid.
Username cannot be empty.

Handling International Characters

The behavior of isalnum() can depend on your Python environment and character encoding. For standard ASCII characters, it's clear.

For characters from other languages, like 'é' or 'α', the result may vary. In many Unicode setups, letters from other scripts are considered alphabetic.

Therefore, isalnum() might return True for them. Understanding your Python character encoding is key for global applications.


# Example 4: Testing with non-ASCII characters
# Note: Output may vary based on locale and Python version
test_international = "Café123"
test_greek = "αλφα12"

print(f"'{test_international}' is alphanumeric: {test_international.isalnum()}")
print(f"'{test_greek}' is alphanumeric: {test_greek.isalnum()}")

'Café123' is alphanumeric: True
'αλφα12' is alphanumeric: True

Combining with Other String Methods

You can combine isalnum() with other checks. For example, you might want to ensure a string starts with a letter.

Python has methods like isalpha() for letters only and isdigit() for numbers only. Use them together for complex rules.


# Example 5: Combined validation
def validate_product_code(code):
    """
    Validates a product code.
    Rule: Must start with a letter, followed by alphanumeric characters.
    """
    if len(code) < 2:
        return False
    # Check if first character is a letter
    if not code[0].isalpha():
        return False
    # Check if the rest (from position 1 onward) is alphanumeric
    if not code[1:].isalnum():
        return False
    return True

# Test the product code validator
codes = ["A123B", "123AB", "AB-12", "Z9"]
for c in codes:
    print(f"Code '{c}': {validate_product_code(c)}")

Code 'A123B': True
Code '123AB': False
Code 'AB-12': False
Code 'Z9': True

Common Pitfalls and Tips

Remember that isalnum() returns False for an empty string. Always check for empty input first if it's a valid case.

The method works on the entire string. To check individual parts, you need to split the string or use a loop.

For more advanced pattern matching, consider using regular expressions (the re module). However, for simple alphanumeric checks, isalnum() is perfect.

Always test with the specific characters you expect in your application, especially if dealing with international text.

Conclusion

Checking for alphanumeric characters is a fundamental task. Python's isalnum() string method provides a clean and efficient solution.

It is ideal for data validation, input sanitization, and parsing text. Remember its behavior with empty strings and non-ASCII characters.

Combine it with other string methods like isalpha() for powerful validation logic. For most use cases, this built-in method is all you need.

Start using isalnum() in your projects to make your string handling more robust and secure.