lettura simple

Python's isalnum() method

Are you working with strings in Python and need to check if they contain only alphanumeric characters? The isalnum() method has got you covered!

string.isalnum()

This method returns True if the string contains only alphabet letters and/or numbers, otherwise, it returns False.

Let's dive into some examples to see how it works.

Suppose you have a string containing a mix of letters and numbers.

>>> my_string = "Hello123"

To check if it's purely alphanumeric, just use the isalnum() method like this:

>>> my_string.isalnum()

Voilà! The method returns True, confirming that the string consists of only letters and numbers.

True

Keep in mind that the isalnum() method will also return True if your string has only letters (e.g., "Hello") or just numbers (e.g., "12345").

But what happens if your string includes a non-alphanumeric character, like an asterisk (*)?

>>> my_string = "Hello123*"

Give the isalnum() method another try:

>>> my_string.isalnum()

This time, it returns False, since our string contains more than just letters and numbers.

False

One cool feature of the isalnum() method is that it can handle Unicode strings, meaning you can use it with any language supported by Python.

For instance, let's try it with a Japanese string.

>>> my_string = "こんにちは123"

Now let's see if it's alphanumeric.

>>> my_string.isalnum()

The method returns True, as the Unicode string "こんにちは123" is a mix of Japanese characters and numbers.

True

So there you have it—a friendly introduction to Python's isalnum() method, your trusty tool for checking alphanumeric strings. Happy coding!




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin