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:
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
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