Python String isalnum() With Examples

Python String isalnum() With Examples

The Python ‘string.isalnum()’ function says ‘True’ if the text has only letters and numbers. If there are no letters or numbers, like if it’s empty, it says ‘False’.

Method 1:

Example 1:

tmp = "HelloAccuCloud"
print(tmp.isalnum())

Output:

True

Explanation:
The output is ‘True’ because the string `tmp` contains only alphanumeric characters (letters and numbers). There are no spaces or special characters in the string.
Example 2:

tmp = "Hello Accu Cloud"
print(tmp.isalnum())

Output:

 False

Explanation:
The output is ‘False’ because the string `tmp` contains spaces in between the words. The `isalnum()` function checks if all the characters in the string are either letters or numbers. In this case, there are spaces in the string, which are not alphanumeric characters, causing the function to return ‘False’.
Example 3:

tmp = ""
print(tmp.isalnum())

Output:

False

Explanation:
The output is ‘False’ because it’s an empty string.
Example 4:

tmp = "X.Y"
print(tmp.isalnum())
tmp1 = "1.2"
print(tmp1.isalnum())

Output:

False
False

Explanation:
Both turn into ‘False’ because there’s a dot (.) in the string, and dots are not counted as alphanumeric characters.
Example 5:

tmp = "౩٤ᚦ"
print(tmp.isalnum())

Output:

True

Explanation:
The result is ‘True’ because these characters are letters. Alphabetic characters are those special symbols marked as “Letter” in the Unicode character list.

Method 2:

Showing all numbers and characters in Python
“We can use the ‘unicode’ module to see if a character is a letter or a number. Here’s a program that shows all the letters and numbers in Unicode.”

import unicodedata
count = 0
for i in range(2 ** 16):
chr = chrs(i)
if chr.isalnum():
print(u'{:04x}: {} ({})'.format(i, chr, unicodedata.name(chr, 'UNNAMED')))
count = count + 1
print(f'Total Number = {count}')

Output:

I only gave a part of the list because there are a lot of letters and numbers in Unicode

Conclusion:

isalnum() in Python checks if a string has only letters or numbers. If a string contains other characters like symbols or spaces, it returns False. It’s handy for verifying alphanumeric content.

Thanks for learning with the Accuweb.Cloud. Check out our offerings for compute, storage, databases. Deploy your Python Application Now!