OneBite.Dev - Coding blog in a bite size

check if a string contains only alphanumeric characters in python

Code snippet on how to check if a string contains only alphanumeric characters in python

testString = 'Testing112@'	
  
if(testString.isalnum() == True): 
  print('String contains only alphanumeric characters')
else:
  print('String contains characters other than alphanumeric')

This code takes a testString and checks if the characters in testString are only alphanumeric characters (letters or numbers). The isalnum() method checks the string and if it only has alphanumeric characters, it returns the Boolean value of True. If the string has any other characters, the isalnum() method returns False.

Then, an if..else statement is used to check the Boolean value. If the value is True, a message is printed saying the string only contains alphanumeric characters. If the value is False, a different message is printed saying the string has other characters too.

python