This is a tutorial of the Python String isalnum() method. Learn to check if all characters in a given string are alphanumeric or not with examples.
str.isalnum() method returns True if the given string contains only alphanumeric characters i.e. only alphabets and numbers. If the given string contains characters other than numbers and alphabets, it will return False.
Given below is the syntax of the Python String
isAlphaNumericOrNot = isalnum()
It does not take any arguments and is simply applied on the string for which you want to check if it contains only alphanumeric characters or not.
isalnum() Return Value
It returns a boolean value i.e. either
False. It returns
True if all the string characters are either alphabets or numbers and
False if at least one of the string character is not a number or an alphabet.
Given below are the two examples demonstrating the usage of the Python String
Example 1. Checking different strings with
Here we are checking five different strings with the
isalnum() method to check which one contains only alphanumeric characters and which one contains other characters.
#String with only Alphabets line = "GurmeetSingh" print(line.isalnum()) #String with only Numbers line = "12345" print(line.isalnum()) #Alphanumeric String line = "Hello12345" print(line.isalnum()) #String with WhiteSpace line = "Gurmeet Singh" print(line.isalnum()) #String with Special Symobls line = "What? It costs $10!" print(line.isalnum())
True True True False False
Example 2. Making use of
isalnum() method with if-else statements
Nothing special but we’ve just used an if-else statement to print a statement according to the boolean value returned by the
line = "I am blogger." if line.isalnum(): print("line is alphanumeric i.e. it only contains alphabets and numbers.") else: print("line is not alphanumeric. It might be containing characters other than just alphabets and numbers.")
line is not alphanumeric. It might be containing characters other than just alphabets and numbers.
You can also use the Python String
isdigit() methods individually to check if the given string only contains either alphabets or numbers respectively.
I hope you found this guide useful. If so, do share it with others who are willing to learn Python and other programming languages. If you have any questions related to this article, feel free to ask us in the comments section.
And do not forget to subscribe to WTMatter!