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

ParameterTypeDescription
xarray_like (StringDType, bytes_, or str_ dtype)Input array containing string elements to be checked.
outndarray, None, or tuple of ndarray and None, optionalOptional output array where results are stored. If None, a new array is created.
wherearray_like, optionalBoolean mask specifying which elements to evaluate. Elements where where=False retain their original value.
castingstr, optionalDefines the casting behavior when evaluating the function.
orderstr, optionalMemory layout order of the output array.
dtypedata-type, optionalDefines the data type of the output array.
subokbool, optionalDetermines 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]