NumPy strings.rindex()

The numpy.strings.rindex() function searches for the last occurrence of a specified substring within an array of strings. If the substring is found, it returns the highest index where it appears; otherwise, it raises a ValueError.

Syntax

</>
Copy
numpy.strings.rindex(a, sub, start=0, end=None)

Parameters

ParameterTypeDescription
aarray-like (np.bytes_ or np.str_ dtype)Input array of strings in which the substring search is performed.
subarray-like (np.bytes_ or np.str_ dtype)The substring to search for within a.
startint, optionalThe starting index for the search. Defaults to 0.
endint, optionalThe ending index for the search. Defaults to None (searches the entire string).

Return Value

Returns an array of integers indicating the highest index where the substring is found in each element of a. If the substring is not found, a ValueError is raised.


Examples

1. Finding the Last Occurrence of a Substring

In this example, we search for the last occurrence of a substring within a string array.

</>
Copy
import numpy as np

# Define an array of strings
arr = np.array(["hello world", "numpy tutorial world", "world of python"], dtype=np.str_)

# Search for the last occurrence of "world"
result = np.strings.rindex(arr, "world")

# Print the result
print("Last index of 'world' in each string:", result)

Output:

Last index of 'world' in each string: [ 6 15  0]

Here, the function returns the last index where “world” appears in each string. If the substring is not found, a ValueError is raised.

2. Using start and end Parameters

We restrict the search within a specific portion of each string.

</>
Copy
import numpy as np

# Define an array of strings
arr = np.array(["search in search", "find the find", "hello world"], dtype=np.str_)

# Search for "search" within index range 5 to end
result = np.strings.rindex(arr, "search", start=5)

# Print the result
print("Last index of 'search' after index 5:", result)

Output:

ValueError: substring not found

The function only considers occurrences of “search” after index 5. If the substring does not appear within the specified range, a ValueError is raised.

3. Handling Strings Without the Substring

When the substring is not found, a ValueError is raised.

</>
Copy
import numpy as np

# Define an array of strings
arr = np.array(["python programming", "machine learning", "deep learning"], dtype=np.str_)

try:
    # Attempt to find "data" in each string
    result = np.strings.rindex(arr, "data")
    print("Last index of 'data':", result)
except ValueError:
    print("Substring 'data' not found in one or more strings.")

Output:

Substring 'data' not found in one or more strings.

Since “data” does not exist in any of the strings, a ValueError is raised and handled using a try-except block.