Skip to content
Home » The isalnum, isalpha and isspace Methods

The isalnum, isalpha and isspace Methods

Spread the love

In my previous articles I covered quite a few string methods. If you haven’t read those articles, feel free to do it. Here they are:

1) formatting methods

2) statistical methods

3) searching methods

4) boolean methods

This article is actually a continuation of the article on string boolean methods. Today we’ll be talking about three methods, which you can use to check whether a given string contains only a specific type of characters, like only letters, digits or white spaces. The methods are isalnum, isalpha and isspace.

Here’s the video version of the article:

The isalnum Method

The method isalnum checks whether the string contains only alphanumeric characters. If so, it returns True. If there is at least one non-alphanumeric character or if the string is empty, it returns False:

>>> text = "abcdef123"
>>> text.isalnum()
True

>>> text = "here are some spaces"
>>> text.isalnum()                  # we also have whitespaces
False

>>> text = "some_characters,()"
>>> text.isalnum()                  # we also have other characters
False

>>> textEmpty = ""
>>> textEmpty.isalnum()             # empty string
False

The isalpha Method

The next method we’ll be talking about is isalpha.

isalpha returns True if the string is not empty and contains only alphabetic characters:

>>> "Please help".isalpha()  # There’s also a space
False

>>> "Help".isalpha()
True

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

The isspace Method

Finally, let’s talk briefly about the isspace method.

isspace returns True if the string contains only whitespace characters, so spaces, newlines, tabs:

>>> "".isspace()  # no characters at all
False

>>> " ".isspace()
True

>>> "          ".isspace()
True

>>> "  \n".isspace()
True

>>> "  \t\t \n  ".isspace()
True

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply