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.
- True if all the characters in the given string are Alphanumerical
- False if any of the characters in the given string are not Alphanumerical
- >>> “Ab12”.isalnum() # returns True since “Ab12” consists only Alphanumerical Characters
- >>> “Ab@12”.isalnum() # returns False since “Ab@12” 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.
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
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
In this example, let’s try isalnum Method with Non-Alphanumerical String i.e. It returns False. Look at the below code.
s2="String@2" 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
String@2 is not Alpha Numeric
Since some of the characters in s2 (i.e. “String@2”) are non-alphanumerical, isalnum Method returned False. So, the Output will be “String@2 is not Alpha Numeric”
For further reference on String Methods, please refer this ->String – Methods