Python String isalnum() Method
The isalnum()
method checks whether all characters in a string are alphanumeric. This means the string can contain letters (a-z, A-Z) and numbers, but it cannot contain any spaces or special characters.
Syntax
string.isalnum()
Parameters
No parameters.
Return Value
Returns True
if all characters in the string are alphanumeric (letters or numbers).
Returns False
if the string contains any non-alphanumeric characters (such as spaces, punctuation marks, or special symbols) or if the string is empty.
Examples
Check if All Characters in a String are Alphanumeric
print("hello".isalnum()) # True
print("123".isalnum()) # True
print("hello22".isalnum()) # True
print("hello bro".isalnum()) # False (contains space)
print("hello!".isalnum()) # False (contains special character)
print("".isalnum()) # False (empty string)
Practical Usage
Let’s ask the user for a username
input and check if it contains only letters and numbers (no spaces or special characters). If the username is valid (alphanumeric), it prints a greeting. Otherwise, it shows an "Invalid Username"
message.
username = input("Enter your username: ")
if username.isalnum():
print(f"Hello, {username}!")
else:
print("Invalid Username")
Output:
For username
: james22
Hello, james22!
For username
: james@22
Invalid Username