Python string isalnum() method returns True if all characters in the string are alphanumeric (either alphabets or numbers). If not, it returns False.
This method is primarily used for validating user inputs, such as in signup forms.
Syntax
string.isalnum()
Parameters
None.
Return value
Returns a boolean value:
- True if all the characters are alphanumeric.
- False if at least one character is not alphanumeric like spaces, punctuation, or other symbols.
Visual Representation
Example 1: How does the String isalnum() Method work?
string = "Ronaldo7"
string2 = "Messi-10"
string3 = "Neymar 11"
#Output for the string1 which is alphanumeric
print(string.isalnum())
#Output for the string2 which is not alphanumeric
print(string2.isalnum())
#Output for the string3 which is not alphanumeric
print(string3.isalnum())
Output
True
False
False
Example 2: Using isalum() with conditions
string = "Ronaldo7"
string2 = "Messi@10"
if(string.isalnum() == True):
print("Ronaldo's name is alphanumeric")
else:
print("Ronaldo's name is not alphanumeric")
if(string2.isalnum() == True):
print("Messi's name is alphanumeric")
else:
print("Messi's name is not alphanumeric")
Output
Ronaldo's name is alphanumeric
Messi's name is not alphanumeric
Special characters like @,#,-, whitespace, and other symbols are not alphanumeric.
Ankit Lathiya is a Master of Computer Application by education and Android and Laravel Developer by profession and one of the authors of this blog. He is also expert in JavaScript and Python development.