NumPy strings.find()
The numpy.strings.find() function searches for a substring within each element of an input string array and returns the lowest index where the substring is found. If the substring is not found, it returns -1. This function is useful for locating specific text within a collection of strings.
Syntax
</>
Copy
numpy.strings.find(a, sub, start=0, end=None)
Parameters
| Parameter | Type | Description |
|---|---|---|
a | array_like | Input string array where the search is performed. |
sub | array_like | The substring to search for within each element. |
start | array_like, optional | The starting index from where to begin searching. Default is 0. |
end | array_like, optional | The ending index (exclusive) where the search should stop. Default is the length of the string. |
Return Value
Returns an array of integers representing the lowest index where the substring is found in each input string. If the substring is not found, it returns -1.
Examples
1. Finding Substring in an Array of Strings
Here, we search for a substring in a list of fruit names.
</>
Copy
import numpy as np
# Define an array of strings
fruits = np.array(["apple", "banana", "cherry", "blueberry"])
# Search for the substring 'an' in each string
result = np.strings.find(fruits, "an")
# Print the results
print("Index positions of 'an':", result)
Output:
Index positions of 'an': [-1 1 -1 -1]
