Skip to content

[Edit]: Python isalnum() #7203

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 142 additions & 19 deletions content/python/concepts/strings/terms/isalnum/isalnum.md
Original file line number Diff line number Diff line change
@@ -1,51 +1,174 @@
---
Title: '.isalnum()'
Description: 'Returns True if all the characters in a given string are alphanumeric.'
Description: 'Returns True if all characters in a string are alphanumeric (letters and numbers).'
Subjects:
- 'Data Science'
- 'Computer Science'
- 'Web Development'
Tags:
- 'Strings'
- 'Methods'
- 'Functions'
- 'Validation'
- 'Booleans'
CatalogContent:
- 'learn-python-3'
- 'paths/analyze-data-with-python'
- 'paths/computer-science'
---

The **`.isalnum()`** string method takes in a string and returns `True` if all the characters are alphanumeric (`A-Z`, `a-z`, `0-9`). Otherwise, it returns `False` if the string contains any non-alphanumeric characters (e.g. `@ # $ % - *`).
The **`.isalnum()`** method is a built-in [string](https://www.codecademy.com/resources/docs/python/strings) method in Python that checks whether all characters in a string are alphanumeric. This method returns `True` if every character in the string is either a letter (a-z, A-Z) or a digit (0-9), and the string contains at least one character. If any character is not alphanumeric or if the string is empty, the method returns `False`.

The `.isalnum()` method is commonly used in data validation scenarios, such as checking usernames, passwords, or any input that should only contain letters and numbers. It's particularly useful in form validation, data cleaning operations, and when processing user inputs where special characters need to be filtered out.

## Syntax

```pseudo
my_string.isalnum()
string.isalnum()
```

This method does not have any parameters.
**Parameters:**

- This method does not accept any parameters.

**Return value:**

## Example
- Returns `True` if all characters in the string are alphanumeric (letters and digits)
- Returns `False` if the string is empty or contains at least one non-alphanumeric character

The examples below use `.isalnum()` to check if all the characters are alphanumeric:
## Example 1: Basic String Validation

This example demonstrates the fundamental usage of `.isalnum()` to check if a string contains only letters and numbers:

```py
my_string = "AlphaNumeric001"
print(my_string.isalnum())
# Check different types of strings
text1 = "Python123" # Contains letters and numbers
text2 = "HelloWorld" # Contains only letters
text3 = "123456" # Contains only numbers

# Test each string
print(f"'{text1}' is alphanumeric: {text1.isalnum()}")
print(f"'{text2}' is alphanumeric: {text2.isalnum()}")
print(f"'{text3}' is alphanumeric: {text3.isalnum()}")

# Test strings with special characters
invalid_text = "Python 123" # Contains space
print(f"'{invalid_text}' is alphanumeric: {invalid_text.isalnum()}")
```

The code above will result in the following output:
The output generated by this code is:

```shell
True
'Python123' is alphanumeric: True
'HelloWorld' is alphanumeric: True
'123456' is alphanumeric: True
'Python 123' is alphanumeric: False
```

## Codebyte Example
This example shows how `.isalnum()` returns `True` for strings containing only letters, only numbers, or a combination of both, but returns `False` when spaces or special characters are present.

## Example 2: Username Validation System

This example demonstrates a practical real-world application of `.isalnum()` for validating user input in a registration system:

```py
def validate_username(username):
"""
Validate username using isalnum() method
Username should only contain letters and numbers
"""
if not username: # Check if empty
return "Username cannot be empty"
elif len(username) < 3:
return "Username must be at least 3 characters long"
elif len(username) > 20:
return "Username must be no more than 20 characters long"
elif not username.isalnum():
return "Username can only contain letters and numbers"
else:
return "Valid username"

# Test different usernames
usernames = ["John123", "user_name", "test@gmail", "Python", "ab", "validuser2024"]

print("Username Validation Results:")
print("-" * 40)
for username in usernames:
result = validate_username(username)
print(f"'{username}': {result}")
```

The output generated by this code is:

```shell
Username Validation Results:
----------------------------------------
'John123': Valid username
'user_name': Username can only contain letters and numbers
'test@gmail': Username can only contain letters and numbers
'Python': Valid username
'ab': Username must be at least 3 characters long
'validuser2024': Valid username
```

The code below is runnable and uses the `.isalnum()` method:
This example shows how `.isalnum()` can be integrated into a comprehensive validation function to ensure usernames meet specific criteria for web applications or user registration systems.

## Codebyte Example: Data Cleaning and Filtering

This example demonstrates using `.isalnum()` for data processing tasks, such as filtering valid product codes from a dataset:

```codebyte/python
my_string_1 = "string2023"
print(my_string_1.isalnum())
def filter_product_codes(code_list):
"""
Filter and categorize product codes based on alphanumeric validation
Valid codes should only contain letters and numbers
"""
valid_codes = []
invalid_codes = []

for code in code_list:
if code.isalnum():
valid_codes.append(code)
else:
invalid_codes.append(code)

return valid_codes, invalid_codes

def generate_report(valid_codes, invalid_codes):
"""Generate a summary report of the filtering process"""
print("Product Code Validation Report")
print("=" * 35)
print(f"Total codes processed: {len(valid_codes) + len(invalid_codes)}")
print(f"Valid codes: {len(valid_codes)}")
print(f"Invalid codes: {len(invalid_codes)}")

if valid_codes:
print(f"\nValid product codes: {', '.join(valid_codes)}")

if invalid_codes:
print(f"\nInvalid product codes: {', '.join(invalid_codes)}")

# Sample product codes from different sources
product_codes = [
"ABC123", "XYZ789", "PROD-001", "TEST_CODE",
"VALID456", "CODE@123", "ITEM#789", "SIMPLE1",
"PRODUCT.CODE", "ALPHA999"
]

my_string_2 = "@lpha"
print(my_string_2.isalnum())
# Process the codes
valid, invalid = filter_product_codes(product_codes)
generate_report(valid, invalid)
```

This example illustrates how `.isalnum()` can be used in data processing workflows to clean and validate data, making it particularly useful for ETL operations or data quality checks.

## Frequently Asked Questions

### 1. Does `.isalnum()` return `True` for an empty string?

No, `.isalnum()` returns `False` for empty strings. The string must contain at least one character, and all characters must be alphanumeric.

### 2. Does `.isalnum()` work with Unicode characters?

Yes, `.isalnum()` works with Unicode letters and digits, not just ASCII characters.

### 3. What's the difference between `.isalnum()` and `.isalpha()` or `.isdigit()`?

`.isalpha()` checks if all characters are letters only, `.isdigit()` checks if all characters are digits only, while `.isalnum()` checks if all characters are either letters or digits (or a combination of both).