Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Return the length of a 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 representing the length of each string element.
Syntax
numpy.char.str_len(a)
Parameters:
- a ? Array-like of str or unicode
Returns: Array of integers representing the length of each string element.
Basic Example
Let's create a simple string array and find the length of each element ?
import numpy as np
# Create array of strings
names = np.array(['Amy', 'Scarlett', 'Katie', 'Brad', 'Tom'])
# Get length of each string element
lengths = np.char.str_len(names)
print("Original array:", names)
print("Lengths:", lengths)
Original array: ['Amy' 'Scarlett' 'Katie' 'Brad' 'Tom'] Lengths: [3 8 5 4 3]
Working with 2D Arrays
The method also works with multi-dimensional string arrays ?
import numpy as np
# Create 2D string array
arr_2d = np.array([['Hello', 'World'],
['Python', 'NumPy']])
# Get lengths element-wise
lengths = np.char.str_len(arr_2d)
print("2D Array:")
print(arr_2d)
print("\nLengths:")
print(lengths)
2D Array: [['Hello' 'World'] ['Python' 'NumPy']] Lengths: [[5 5] [6 5]]
Detailed Example
Here's a complete example showing array properties and string length calculation ?
import numpy as np
# Create a One-Dimensional array of strings
arr = np.array(['Amy', 'Scarlett', 'Katie', 'Brad', 'Tom'])
# Display array information
print("Array...\n", arr)
print("\nArray datatype...\n", arr.dtype)
print("\nArray Dimensions...\n", arr.ndim)
print("\nOur Array Shape...\n", arr.shape)
print("\nNumber of elements in the Array...\n", arr.size)
# Get string lengths element-wise
print("\nResult (length element-wise)...\n", np.char.str_len(arr))
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]
Conclusion
The numpy.char.str_len() function efficiently calculates string lengths element-wise for NumPy arrays. It works with both 1D and multi-dimensional string arrays, returning an integer array with corresponding lengths.
