W3Basic Logo

Python String isalnum() Method

The str.isalnum() method returns True if all the characters in the string are alphanumeric (either alphabets or numbers); otherwise, it returns False.

What are Alphanumeric characters?

Alphanumerical or alphanumeric characters are a combination of alphabetical and numerical characters. The str.isalnum() method checks whether the characters in the string are alphanumeric or not.

Example:

text = "Year2022"
print(text.isalnum())

Output

True

Syntax

The Syntax of the str.isalnum() function is:

str.isalnum()

Here, str is a string.

Parameters

The str.isalnum() function does not take any parameters.

Return Value

The str.isalnum() function returns:

  • True - if all the characters in the string are alphanumeric.
  • False - if at least one of the characters in the string is non-alphanumeric or an empty string,

Note: The empty strings are considered non-alphanumeric, and the method returns False.

Example 1: Python Program to check if the string is alphanumeric

In the below example, the isalnum() method returns True if all the characters in the string are alphabets, numbers, or alphanumeric and if one of the characters in the string has a non-alphanumeric character (Space, Tab, special characters, etc.) or an empty string, it returns False.

# String contains only alphabets
text = "Hello"
print(text.isalnum())

# String contains only numbers
text = "Hello"
print(text.isalnum())

# String contains alphabets and numbers
text = "Python310"
print(text.isalnum())

# String contains alphabets, numbers, and space
text = "Python310 is the latest version"
print(text.isalnum())

# String contains non-alphanumeric character
text = "Python3.10"
print(text.isalnum())

Output

True
True
True
False
False

Example 2: Python Program to verify if a given string is Alphanumeric

In the below program, we read the username as input from the user, and we have written a user-defined function verify_username() that checks if the username is valid alphanumeric or not using the isalnum() method.

# Method to check if the username is alphanumeric or not
def verify_username(username):

    if (username.isalnum()):
        return "The username entered is valid alphanumeric"
    else:
        return "The username entered is not valid alphanumeric"


text = input("Enter Username: ")
print(verify_username(text))

Output

Enter Username: Jack123
The username entered is a valid alphanumeric

Enter Username: Chandler_Bing
The username entered is not a valid alphanumeric

Reference: Python Official Docs

© 2023 W3Basic. All rights reserved.

Follow Us: