NumPy strings.isalpha()

The numpy.strings.isalpha() function checks whether all characters in each element of an input array are alphabetic and contain at least one character. It returns True if all characters are alphabetic, otherwise False.

Syntax

</>
Copy
numpy.strings.isalpha(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 check for alphabetic characters.
outndarray, None, or tuple of ndarray and None, optionalOptional output array where the result is stored. If None, a new array is created.
wherearray_like, optionalBoolean mask specifying which elements to check. If False, the output retains its original value.
castingstr, optionalDefines the casting behavior when applying 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 indicating whether each element consists only of alphabetic characters. If the input is a scalar, a scalar boolean is returned.


Examples

1. Checking Alphabetic Strings

We check if the given strings contain only alphabetic characters.

</>
Copy
import numpy as np

# Define an array of strings
fruits = np.array(["apple", "banana", "cherry", "123", "grape1", ""])

# Check if each element contains only alphabetic characters
result = np.strings.isalpha(fruits)

# Print the results
print("Input strings:", fruits)
print("Is alphabetic:", result)

Output:

Input strings: ['apple' 'banana' 'cherry' '123' 'grape1' '']
Is alphabetic: [ True  True  True False False False]

2. Using the out Parameter

Storing the results in a predefined output array.

</>
Copy
import numpy as np

# Define an array of strings
fruits = np.array(["mango", "orange", "123fruit", "berry", " "])

# Create an output array with the same shape
output_array = np.empty(fruits.shape, dtype=bool)

# Apply isalpha function and store the results in output_array
np.strings.isalpha(fruits, out=output_array)

# Print the results
print("Computed results:", output_array)

Output:

Computed results: [ True  True False  True False]

3. Using the where Parameter

Checking alphabetic values only for specific elements using a condition.

</>
Copy
import numpy as np

# Define an array of strings
words = np.array(["kiwi", "strawberry", "plum12", "melon", "23blueberry"])

# Define a mask (check only where mask is True)
mask = np.array([True, False, True, True, False])

# Apply isalpha function where mask is True
result = np.strings.isalpha(words, where=mask)

# Print the results
print("Filtered isalpha results:", result)

Output:

Filtered isalpha results: [ True False False  True False]

The function checks only the elements where mask=True. The other values remain unchanged.