NumPy strings.isalnum()
The numpy.strings.isalnum() function checks whether all characters in each element of an input array are alphanumeric (letters and numbers) and whether there is at least one character. If all characters in a string are alphanumeric, it returns True; otherwise, it returns False.
Syntax
</>
Copy
numpy.strings.isalnum(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)
Parameters
| Parameter | Type | Description |
|---|---|---|
x | array_like (StringDType, bytes_ or str_ dtype) | Input array containing strings to check. |
out | ndarray, None, or tuple of ndarray and None, optional | Optional output array where the result is stored. If None, a new array is created. |
where | array_like, optional | Boolean mask specifying which elements to evaluate. Elements where where=False retain their original value. |
casting | str, optional | Defines the casting behavior during computation. |
order | str, optional | Specifies memory layout order of the output array. |
dtype | data-type, optional | Defines the data type of the output array. |
subok | bool, optional | Determines whether subclasses of ndarray are preserved in the output. |
Return Value
Returns an array of boolean values where True indicates that all characters in the corresponding input string are alphanumeric, and False otherwise. If the input is a scalar, the output is a scalar boolean.
Examples
1. Checking Alphanumeric Strings in an Array
In this example, we check if each string in an array contains only alphanumeric characters.
</>
Copy
import numpy as np
# Define an array of strings
fruits = np.array(["apple", "banana123", "cherry!", "mango"])
# Check if each string is alphanumeric
result = np.char.isalnum(fruits)
# Print the results
print("Input strings:", fruits)
print("Alphanumeric check:", result)
Output:
Input strings: ['apple' 'banana123' 'cherry!' 'mango']
Alphanumeric check: [ True True False True]
