Python string type provides the method isalnum()
in order to check the current string characters if they are alphanumeric. All characters are tested and if all characters are alphanumeric the method isalnum() method returns True. At least one character is not alphanumeric the method isalnum() method returns False.
isalnum() Method Syntax
The isalnum() method has the following simple syntax.
STRING.isalnum()
- STRING is a string value or string variable where the characters are checked if they are alphanumeric or not.
The isalnum() method does not take any parameters and returns boolean values True or False. The isalnum() returns True is all characters of the specified string are alphanumeric. Returns False if at least one character of the string is not alphanumeric.
Check If Specified String Is AlphaNumeric
A string can be checked if it is alphanumeric or not by using the isalnum() method. As stated previously all characters are checked in the background and if all characters are alpha numeric this method returns True.
a="ismail"
print(a.isalnum())
b="pythontect.com"
print(b.isalnum())
c="pythontect123"
print(c.isalnum())
d="pythontect com"
print(d.isalnum())
e="123"
print(e.isalnum())
True False True False True
Alternatively the string can be checked without creating a variable if it is alphanumeric. Just create a string value and call the isalnum() method like below.
print("ismail".isalnum())
print("pythontect.com".isalnum())
print("pythontect123".isalnum())
print("pythontect com".isalnum())
print("123".isalnum())
Check If Specified Input Is AlphaNumeric
Another use case for the isalnum() method is checking the user input if it is alphanumeric. The user input can be checked if it is alphanumeric. The user input can be taken with the input() method. The input() method returns the user input as a string and the isalnum() method can be executed over user input.
input=input()
print(input.isalnum())
isalnum() Method vs isalpha() Method
The method isalnum() is used to check if the specified string variable or string value is copmletely alphanumeric. The method isalpha()
is used to check if the specified string variable or string value is completely alphabetic. The difference is isalpha() method only checks for alphabetic characters and not the numeric characters.