Python String isalnum() Method

Python String Isalnum() Method

This is a tutorial of the Python String isalnum() method. Learn to check if all characters in a given string are alphanumeric or not with examples.

Python String isalnum()

The Python str.isalnum() method returns True if the given string contains only alphanumeric characters i.e. only alphabets and numbers. If the given string contains characters other than numbers and alphabets, it will return False.

Syntax

Given below is the syntax of the Python String isalnum() method.

isalnum() Parameters

It does not take any arguments and is simply applied on the string for which you want to check if it contains only alphanumeric characters or not.

isalnum() Return Value

It returns a boolean value i.e. either True or False. It returns True if all the string characters are either alphabets or numbers and False if at least one of the string character is not a number or an alphabet.

Examples

Given below are the two examples demonstrating the usage of the Python String isalnum() method.

Example 1. Checking different strings with isalnum() method

Here we are checking five different strings with the isalnum() method to check which one contains only alphanumeric characters and which one contains other characters.

#String with only Alphabets
line = "GurmeetSingh"
print(line.isalnum())

#String with only Numbers
line = "12345"
print(line.isalnum())

#Alphanumeric String
line = "Hello12345"
print(line.isalnum())

#String with WhiteSpace
line = "Gurmeet Singh"
print(line.isalnum())

#String with Special Symobls
line = "What? It costs $10!"
print(line.isalnum())

Output.

True
True
True
False
False

Example 2. Making use of isalnum() method with if-else statements

Nothing special but we’ve just used an if-else statement to print a statement according to the boolean value returned by the isalnum() method

line = "I am blogger."

if line.isalnum():
    print("line is alphanumeric i.e. it only contains alphabets and numbers.")
else:
    print("line is not alphanumeric. It might be containing characters other than just alphabets and numbers.")

Output.

line is not alphanumeric. It might be containing characters other than just alphabets and numbers.

You can also use the Python String isalpha() and isdigit() methods individually to check if the given string only contains either alphabets or numbers respectively.

I hope you found this guide useful. If so, do share it with others who are willing to learn Python and other programming languages. If you have any questions related to this article, feel free to ask us in the comments section.

And do not forget to subscribe to WTMatter!

Subscribe To WTMatter!

Receive updates of our latest articles via email. Enter your email address below to get started.

Leave a Reply

Your email address will not be published. Required fields are marked *