Python String isalnum() Method

The isalnum() method returns True if all characters in the string are alphanumeric (either alphabets or numbers). If not, it returns False.

Syntax:

str.isalnum()

Parameters:

No parameters.

Return Value:

Returns True if all characters in the string are alphanumeric and returns False even if one character is not alphanumeric.

The following example demonstrates isalnum() method.

Example: isalnum()
mystr = 'Hello123'
print(mystr.isalnum())

mystr = '12345'
print(mystr.isalnum())

mystr = 'TutorialsTeacher'
print(mystr.isalnum())
Output
True
True
True

The isalnum() method will return False if the string consists of whitespaces and symbols.

Example: isalnum()
mystr = 'Python is a programming language.'
print(mystr.isalnum())

mystr = '#1'
print(mystr.isalnum())

mystr = 'Hello\tWorld'
print(mystr.isalnum())
Output
False
False
False

The isalnum() method can be used to identify non-alphanumerics in a string, as shown below.

Example: Separate Non-alphanumeric
def printNonAlphanumeric(str):
	print('non-alphanumerics:', end='')
	for i in str:
		if(i.isalnum() == False):
			print(i,end=',')
            
printNonAlphanumeric('*@TutorialsTeacher #123')

Output
non-alphanumerics:*,@, ,#,

The following table lists difference among the isalpha(), isalnum(), and isidentifier() methods based on the given inputs:

Input String isaplha() isalnum() isidentifier()
'123' False True False
'$123' False False False
'XYZ123' False True True
'123XYZ' False True False
'_123XYZ' False False True
'_XYZ_123' False False True
'-XYZ-123' False False False
'.XYZ.123' False False False
Want to check how much you know Python?