Python 3 – String isalnum() Method
The isalnum() method is an in-built function in Python 3 programming language that is used to check whether a string contains only alphanumeric characters or not. The isalnum() method returns True if all the characters in the string are alphanumeric (letters and numbers), and there is at least one character. Otherwise, it returns False.
Syntax
string.isalnum()
Return Value
The isalnum() method returns a boolean value — True or False, depending on whether the string contains only alphanumeric characters or not.
Example
The following example shows how to use the isalnum() method in Python:
str1 = 'abc123'
print(str1.isalnum()) # Output: True
str2 = 'abc$123'
print(str2.isalnum()) # Output: False
str3 = '12 34'
print(str3.isalnum()) # Output: False
str4 = ''
print(str4.isalnum()) # Output: False
The first example returns True, as the string ‘abc123’ contains only alphabets and numbers.
The second example returns False because the string ‘abc$123′ contains a special character along with the alphabets and numbers.
The third example also returns False because the string ’12 34’ contains a space character.
The fourth example returns False because the string is empty and doesn’t contain any characters.
Conclusion
The isalnum() method is a useful in-built function in Python that can be used to check if a string contains only alphanumeric characters. It returns a boolean value that indicates whether the string is alphanumeric or not. By using the isalnum() method, we can write more efficient and robust programs that handle strings the right way.