Return Length of String Array Element-wise in Python



To return the length of a string array element-wise, use the numpy.char.str_len() method in Python Numpy. The method returns an output array of integers.

Steps

At first, import the required library −

import numpy as np

Create a One-Dimensional array of strings −

arr = np.array(['Amy', 'Scarlett', 'Katie', 'Brad', 'Tom'])

Displaying our array −

print("Array...\n",arr)

Get the datatype −

print("\nArray datatype...\n",arr.dtype)

Get the dimensions of the Array −

print("\nArray Dimensions...\n",arr.ndim)

Get the shape of the Array −

print("\nOur Array Shape...\n",arr.shape)

Get the number of elements of the Array −

print("\nNumber of elements in the Array...\n",arr.size)

To return the length of a string array element-wise, use the numpy.char.str_len() method −

print("\nResult (length element-wise)...\n",np.char.str_len(arr))

Example

import numpy as np

# Create a One-Dimensional array of strings
arr = np.array(['Amy', 'Scarlett', 'Katie', 'Brad', 'Tom'])

# Displaying our array
print("Array...\n",arr)

# Get the datatype
print("\nArray datatype...\n",arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)

# Get the number of elements of the Array
print("\nNumber of elements in the Array...\n",arr.size)

# To return the length of a string array element-wise, use the numpy.char.str_len() method in Python Numpy
# The method returns an output array of integers.

print("\nResult (length element-wise)...\n",np.char.str_len(arr))

Output

Array...
['Amy' 'Scarlett' 'Katie' 'Brad' 'Tom']

Array datatype...
<U8

Array Dimensions...
1

Our Array Shape...
(5,)

Number of elements in the Array...
5

Result (length element-wise)...
[3 8 5 4 3]
Updated on: 2022-02-24T08:05:40+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements