bytes.isalnum() returns True if the bytes object is not empty and every byte is an ASCII letter (a-z, A-Z) or an ASCII digit (0-9). Otherwise it returns False.
Spaces, underscores, hyphens, control bytes, and all bytes from 128 to 255 make the result False. That is a quick way to check that an identifier received over the network uses only safe ASCII characters.
bytes.isalnum() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.isalnum(...). No import is needed, and bytearray objects have the same method.
Syntax
No arguments; returns a bool.
python
result = data.isalnum()
Call
What it does
b"abc123".isalnum()
Returns True.
b"abc_123".isalnum()
Returns False: underscore.
b"".isalnum()
Returns False: empty.
isalnum() is true exactly when every byte passes isalpha() or isdigit().
Method signatures
python
bytes.isalnum()
# returns True or False; bytearray.isalnum() works the same way
Parameters
isalnum() takes no parameters.
Return Value
Return Value
Description
True
At least one byte, and all bytes are ASCII letters or digits.
False
The object is empty or contains any other byte.
Python Examples
Example 1 — Check Several Byte Strings
Run the check on plain tokens, a token with a space, empty bytes, encoded text, and a short code.
python
samples = [b"abc123", b"abc 123", b"", b"caf\xc3\xa9", b"X9"]
for s in samples:
print(s, s.isalnum())