NumPy strings.isspace()
The numpy.strings.isspace() function checks whether each element in a string array consists only of whitespace characters and contains at least one character.
It returns True for such elements and False otherwise.
Syntax
</>
Copy
numpy.strings.isspace(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 string elements to be checked. |
out | ndarray, None, or tuple of ndarray and None, optional | Optional output array where results are 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 when evaluating the function. |
order | str, optional | Memory layout order of the output array. |
dtype | data-type, optional | Defines the data type of the output array. |
subok | bool, optional | Determines if subclasses of ndarray are preserved in the output. |
Return Value
Returns a boolean array where each element is True if the corresponding string consists only of whitespace characters, and False otherwise. If the input is a scalar, a scalar boolean is returned.
Examples
1. Checking if Strings Contain Only Whitespace
In this example, we check if various string elements in an array consist only of whitespace characters.
</>
Copy
import numpy as np
# Define an array of strings
strings = np.array([" ", "hello", "\t\n", "", " word "])
# Check which strings contain only whitespace
result = np.char.isspace(strings)
# Print the result
print("Input strings:", strings)
print("Contains only whitespace:", result)
Output:
Input strings: [' ' 'hello' '\t\n' '' ' word ']
Contains only whitespace: [ True False True False False]
