Python

Python String Method: isalnum()

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).

Usage

The syntax for using the isalnum() method is as follows:

    string.isalnum()

This method does not take any parameters. It returns either True or False depending on whether the condition is met or not.

Walkthrough

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’).

Note:

  • If there are spaces within the string or special characters such as @,#,$,% etc., then isalnum() will return False.
  • The 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:

  1. Create a new Python file or open your Python interpreter.
  2. Type in a variable name followed by an equal sign and your chosen string. For example:
    sentence = "HelloWorld"
  3. Next, use the isalnum() method by typing in your variable name followed by .isalnum(). For example:
    result = sentence.isalnum()
  4. Print out the result using the print function. For example:
    print(result)

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.

In Conclusion

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!

Leave a Reply

Your email address will not be published. Required fields are marked *