Python String isalnum()
Method
The isalnum() method in Python is used to check whether a string contains only letters and numbers (alphanumeric characters). It’s a built-in method available for string objects.
Syntax
string.isalnum()
Parameters:
- This method does not take any parameters.
Returns:
True
– if all characters in the string are alphanumeric (letters or digits) and there is at least one character.False
– if the string contains any special characters, spaces, or is empty.
Example 1: Alphanumeric String
text = "Python3"
print(text.isalnum())
True
Example 2: String with Spaces
text = "Hello World"
print(text.isalnum())
False
Example 3: String with Special Characters
text = "Python@123"
print(text.isalnum())
False
Example 4: Empty String
text = ""
print(text.isalnum())
False
Use Case: Validating Usernames
The isalnum()
method is commonly used when checking for valid usernames or codes where only letters and numbers are allowed.
username = input("Enter a username: ")
if username.isalnum():
print("Valid username.")
else:
print("Username must be alphanumeric.")
Common Mistakes
- Expecting
isalnum()
to return True for strings with spaces (it won’t). - Using it on an empty string – it will return False.
Summary
string.isalnum()
checks if all characters are letters or digits.- Returns
True
only when the string has no special characters or spaces. - Empty strings return
False
.
Practice Problem
Write a program that checks whether a user’s input is a valid product code made of letters and numbers only.
product_code = input("Enter product code: ")
if product_code.isalnum():
print("Valid code.")
else:
print("Code should only contain letters and numbers.")