NumPy strings.istitle()

The numpy.strings.istitle() function checks whether each string element in an array is titlecased. A string is considered titlecased if each word starts with an uppercase letter followed by lowercase letters and contains at least one character.

Syntax

</>
Copy
numpy.strings.istitle(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 of strings to check.
outndarray, None, or tuple of ndarray and None, optionalOptional output array to store results. If None, a new array is created.
wherearray_like, optionalBoolean mask determining which elements should be checked.
castingstr, optionalDefines the casting behavior.
orderstr, optionalSpecifies memory layout order.
dtypedata-type, optionalSpecifies the data type of the output array.
subokbool, optionalDetermines if subclasses of ndarray are preserved.

Return Value

Returns a boolean array indicating whether each string element in x is titlecased. If x is a scalar, a single boolean value is returned.


Examples

1. Checking Titlecase Strings in an Array

In this example, we check if each string in an array is titlecased.

</>
Copy
import numpy as np

# Define an array of strings
strings = np.array(["Hello World", "python programming", "Data Science", "Machine Learning"])

# Check if each string is titlecased
result = np.char.istitle(strings)

# Print the results
print("Input Strings:", strings)
print("Titlecase Check:", result)

Output:

Input Strings: ['Hello World' 'python programming' 'Data Science' 'Machine Learning']
Titlecase Check: [ True False  True  True]

2. Using the out Parameter

We store the result in an existing output array.

</>
Copy
import numpy as np

# Define an array of strings
strings = np.array(["NumPy Library", "python code", "Deep Learning"])

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

# Check titlecase and store results in output_array
np.char.istitle(strings, out=output_array)

# Print the results
print("Stored in Output Array:", output_array)

Output:

Stored in Output Array: [ True False  True]

3. Using the where Parameter

Using a condition to check titlecase only for specific elements.

</>
Copy
import numpy as np

# Define an array of strings
strings = np.array(["Machine Learning", "computer vision", "Data Science"])

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

# Check titlecase where mask is True
result = np.char.istitle(strings, where=mask)

# Print the results
print("Titlecase Check with Mask:", result)

Output:

Titlecase Check with Mask: [ True False  True]

The function checks titlecase only for elements where mask=True. The second element is ignored.