NumPy strings.index()
The numpy.strings.index() function searches for a substring within a given string or an array of strings.
It works similarly to find(), but instead of returning -1 when the substring is not found, it raises a ValueError.
Syntax
</>
Copy
numpy.strings.index(a, sub, start=0, end=None)
Parameters
| Parameter | Type | Description |
|---|---|---|
a | array-like (StringDType, bytes_, or str_ dtype) | The input string or array of strings to search within. |
sub | array-like (StringDType, bytes_, or str_ dtype) | The substring to find within a. |
start | array_like (integer), optional | Starting position of the search. Defaults to 0. |
end | array_like (integer), optional | Ending position of the search. Defaults to searching the entire string. |
Return Value
Returns an array of integers indicating the index of the first occurrence of the substring in each string. If the substring is not found, it raises a ValueError.
Examples
1. Finding the Index of a Substring
In this example, we find the position of a substring within a given string.
</>
Copy
import numpy as np
# Define a string
word = np.array("apple")
# Find the index of the substring "p"
result = np.strings.index(word, "p")
# Print the result
print("Index of 'p' in 'apple':", result)
Output:
Index of 'p' in 'apple': 1
