Python isalnum: String Is AlphanumericUse the isalnum method to see whether a string contains only letters and digits.
Isalnum. Sometimes we want to ensure a string contains not punctuation or other whitespace. We want to see if the string 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 weird characters are found, it returns false.
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.
Tests: We have 7 strings in our tests list. Some have spaces, punctuation, and one is an empty string.Strings
Result: The only strings that cause isalnum to return true are the ones with no whitespace or punctuation (and at least 1 character).
Python program that uses isalnum method
tests = 
tests.append("Dot Net Perls")
for test in tests:
# Test each string for alphanumeric status with isalnum.
print("isalnum: [", test, "]")
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.DictionaryList
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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.