Check if all Characters of String are Alphanumeric or not in Python

In this tutorial, you will learn about how to check if all characters of String are Alphanumeric or not in Python. String Class consists of various pre-defined Methods. We mainly use isalnum() Method of String Class. So, let’s continue reading.

About isalnum Method:

The isalnum Method is a pre-defined Method of String Class i.e. it can be used for every String Object. It returns Boolean Values based on the criteria given below.

It returns

  • True if all the characters in the given string are Alphanumerical
  • False if any of the characters in the given string are not Alphanumerical

For Example,

  1. >>> “Ab12”.isalnum()      # returns True since “Ab12” consists only Alphanumerical Characters
  2. >>> “[email protected]”.isalnum()    # returns False since “[email protected]” consists 1 Special Character i.e. ‘@’

To know more about isalnum Method, Click Here -> String – isalnum – PyDocs

Python Program to check Alphanumerical Characters:

Enough Intro. Now, we intend to check whether all the Characters in a given String are Alphanumeric are not in Python. Let’s have a look at the following examples.

Example 1:

In this example, let’s try isalnum Method with Alpha-Numeric String i.e. It returns True. Look at the below code

s1="String1"
val=s1.isalnum()
if(val==True): 
    print(s1,"is Alpha Numeric") 
else:
    print(s1,"is not Alpha Numeric")

Here, val holds Boolean Value as said above. Hence, the output of the above code will be as follows

Output:

String1 is Alpha Numeric

Since all the characters in s1 (i.e. “String1”) are alphanumerical, isalnum Method returned True. Let’s have a look at another example

Example 2:

In this example, let’s try isalnum Method with Non-Alphanumerical String i.e. It returns False. Look at the below code.

s2="[email protected]"
val=s2.isalnum()
if(val==True):
    print(s2,"is Alpha Numeric")
else:
    print(s2,"is not Alpha Numeric")

From the above code, the output of the above code will be as follows

Output:

[email protected] is not Alpha Numeric

Since some of the characters in s2 (i.e. “[email protected]”) are non-alphanumerical, isalnum Method returned False. So, the Output will be “[email protected] is not Alpha Numeric”

For further reference on String Methods, please refer this ->String – Methods

 

Leave a Reply

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