In this tutorial, we’ll learn what Python string isalnum() method is and how to properly use it with the help of an easy and detailed multiple Python code examples.
Introduction: Python String isalnum() Method
This method is used to return true if a specific string only consists of alphanumeric(alphabets of numbers). If not, then it will return false.
Syntax of isalnum() Method
string.isalnum()
- Python string isalnum method does not take any arguments.
- It returns True if the string is alphanumeric, or else it returns False.
Example 1: isalnum() applied on a String
str='Python3Language' print( str.isalnum() )
Output
True
It returns True as the string has only numbers and alphabets.
Let’ give our string some space. See below code:
str='Python3 Language' print( str.isalnum() )
Output
False
As we’ve already mentioned above that Python string isalnum() method will return True when the string has only alphabets or numbers. But in the above string, we also have passed a space. So the result is False.
See some more examples below:
print('Python'.isalnum()) // True print('23455.6'.isalnum()) // decimal will also return False print('23455'.isalnum()) // True print('Python_Programming'.isalnum()) // False print('Python-Programming'.isalnum()) // False print('@PythonProgramming'.isalnum()) // False print('Python_Programming#'.isalnum()) // False
Output
True False True False False False False
Example 2: isalnum() Return Value
returnedVal='Python'.isalnum() print(returnedVal)
Output
True
Python string isalnum() method returns True if the string is alphanumeric, or else it returns False.
Example 3: Use isalnum() Method in Python If Else Condition
val='Python3ProgrammingLanguage' if val.isalnum(): print(val+' is alphamnumeric') else: print(val+' is not alphamnumeric')
Output
Python3ProgrammingLanguage is alphamnumeric
Example 4: Use isalnum() Method in Python For Loop
val='Python3_Language*' for i in val: if i.isalnum(): print(i+' is alphamnumeric') else: print(i+' is not alphamnumeric')
Output
P is alphamnumeric y is alphamnumeric t is alphamnumeric h is alphamnumeric o is alphamnumeric n is alphamnumeric 3 is alphamnumeric _ is not alphamnumeric L is alphamnumeric a is alphamnumeric n is alphamnumeric g is alphamnumeric u is alphamnumeric a is alphamnumeric g is alphamnumeric e is alphamnumeric * is not alphamnumeric
Using this method, we can check each and every item of a string individually.
Conclusion
To conclude this tutorial, hope you now have an in-depth practical knowledge of how to properly use Python string isalnum method. I’ll love to have your valuable feedback. Thank you for reading this post.