NumPy strings.str_len()

The numpy.strings.str_len() function computes the length of each element in an array of strings. For byte strings, it returns the number of bytes, while for Unicode strings, it returns the number of Unicode code points.

Syntax

</>
Copy
numpy.strings.str_len(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)

Parameters

ParameterTypeDescription
xarray_likeArray of strings (byte strings or Unicode strings).
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 compute. Elements where where=False retain their original value.
castingstr, optionalDefines the casting behavior when computing string lengths.
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 an array of integers representing the length of each string in the input array. If the input is a scalar, a scalar is returned.


Examples

1. Computing the Length of a Single String

Here, we compute the length of a single string.

</>
Copy
import numpy as np

# Define a string
string = np.array("NumPy")

# Compute the length of the string
length = np.strings.str_len(string)

# Print the result
print("Length of the string:", length)

Output:

Length of the string: 5

2. Computing String Lengths in an Array

We compute the lengths of multiple strings in an array.

</>
Copy
import numpy as np

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

# Compute the length of each string
lengths = np.strings.str_len(strings)

# Print the results
print("Strings:", strings)
print("Lengths:", lengths)

Output:

Strings: ['apple' 'banana' 'cherry' 'fig']
Lengths: [5 6 6 3]

3. Using the out Parameter

Using an output array to store results instead of creating a new array.

</>
Copy
import numpy as np

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

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

# Compute string lengths and store the result in output_array
np.strings.str_len(strings, out=output_array)

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

Output:

Strings: ['apple' 'banana' 'cherry' 'fig']
Lengths: [5 6 6 3]

4. Using the where Parameter

Using a condition to compute string lengths only for selected elements.

</>
Copy
import numpy as np

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

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

# Compute string lengths where mask is True
result = np.strings.str_len(strings, where=mask)

# Print the results
print("Computed string lengths with mask:", result)

Output:

Computed string lengths with mask: [ 5  0  5  0]

The string lengths are computed only for elements where mask=True. The other values remain unchanged.