Home
Python
String isalnum Example
Updated Oct 9, 2021
Dot Net Perls
Isalnum. Sometimes we want to ensure a Python string has no punctuation or other whitespace. We can see if it contains just letters and digits.
With isalnum, we have a method that loops over the characters in the string. If any whitespace, punctuation, or other characters are found, it returns false.
string Punctuation
An example. Here we see a program that uses isalnum. We can call isalnum() on a string instance, or use str.isanum and pass the string as the argument.
Detail We have 7 strings in our tests list. Some have spaces, punctuation, and one is an empty string.
Result The only strings that cause isalnum to return true are the ones with no whitespace or punctuation (and at least 1 character).
tests = [] tests.append("Dot Net Perls") tests.append("DotNetPerls") tests.append("Dot_Net_Perls") tests.append("Dot0123") tests.append("dotnetperls") tests.append("123") tests.append("") for test in tests: # Test each string for alphanumeric status with isalnum. if test.isalnum(): print("isalnum: [", test, "]") else: print("false: [", test, "]")
false: [ Dot Net Perls ] isalnum: [ DotNetPerls ] false: [ Dot_Net_Perls ] isalnum: [ Dot0123 ] isalnum: [ dotnetperls ] isalnum: [ 123 ] false: [ ]
A useful method. Often we want to validate strings before putting them into a dictionary or list. Isalnum is a good method to remember—it is easier than trying to write a similar method.
Dictionary
String List
A review. When possible, methods like isalnum() from the standard library should be reused. They do not need testing—they are convenient and easy to understand.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 9, 2021 (edit).
Home
Changes
© 2007-2025 Sam Allen