Checking if a string consists of alphanumeric characters in Python?

Python Methods and Functions

The Python String class has an isalnum () method that can be called on a string and tells us if the string consists of alphanumeric characters only or not. You can call it like this:

 print ('123abc'.isalnum ()) 

OUTPUT

 True 
 print ('123 # $% abc'.isalnum ()) 

OUTPUT



 False 

You can also use regular expressions for the same result. To match literal numbers, we can call re.match (regex, string) using the regular expression: "^ [a-zA-Z0-9] + $". For example,



 import re print (bool (re.match ('^ [a-zA-Z0-9] + $', '123abc'))) 

OUTPUT

 True 
 import re print (bool (re.match ('^ [a-zA-Z0-9] + $ ',' 123abc # $% '))) 

OUTPUT

 False 

re.match returns an object, to check if it exists or not, we need to convert it to boolean using bool ().


< br>





Get Solution for free from DataCamp guru