In this tutorial, we will be discussing one of Python’s built-in string methods,
isalnum(). This method is used to check if all the characters in a text are alphanumeric (a combination of alphabets and numbers).
The syntax for using the
isalnum() method is as follows:
This method does not take any parameters. It returns either True or False depending on whether the condition is met or not.
To understand how this works, let’s consider an example:
text = "Python123" result = text.isalnum() print(result)
In this case, the output would be ‘True’ because all characters in “Python123” are either letters (i.e., ‘Python’) or numbers (i.e., ‘123’).
- If there are spaces within the string or special characters such as @,#,$,% etc., then
isalnum()will return False.
isalnum()function doesn’t take any arguments.
- An empty string always returns False.
Tutorial: Using Python’s isalnum() Method
To use Python’s
isalnum(), follow these steps:
- Create a new Python file or open your Python interpreter.
- Type in a variable name followed by an equal sign and your chosen string. For example:
sentence = "HelloWorld"
- Next, use the
isalnum()method by typing in your variable name followed by .isalnum(). For example:
result = sentence.isalnum()
- Print out the result using the print function. For example:
If you’ve followed these steps correctly, your Python interpreter should return either True or False depending on whether all characters in your string are alphanumeric.
The Python isalnum() method is a simple and effective way to check if a string contains only alphanumeric characters. It’s an essential tool for data validation and cleaning tasks in various programming scenarios.
We hope this tutorial has been helpful in understanding how to use Python’s built-in isalnum() method. Happy coding!