What is the numpy.char.rfind() function from NumPy in Python?

Overview

The char.rfind() function in Python returns the highest index in an input array's string where the sub substring is found. This is such that the sub is contained within [start, end].

Syntax

char.rfind(a, sub, start=0, end=None)
Syntax for the char.rfind() function

Parameter value

The char.rfind() function takes the following parameter values:

  • a: This is the input array. It is required.
  • sub: This is the substring to be searched for. It is required.
  • start, end: These are optional arguments interpreted as in slice notation.

Return value

The char.rfind() function returns an output array of integers. It returns -1 if the sub is not found.

Example

import numpy as np
# creating an input array
a = np.array(['What', "makes you", "happy?"])
# creating the substring
sub = "ou"
# implementing the char.rfind() function
myarray = np.char.rfind(a, sub, start=1, end=None)
# printing the input array
print(a)
# printing the output arrays
print(myarray)

Explanation

  • Line 1: We import the numpy module.
  • Line 3: We create an input array a using the array() function.
  • Line 6: We create the substring variable sub.
  • Line 9: We implement the char.rfind() function on the input array. The result is assigned to a variable myarray.
  • Line 12: We print the input array a.
  • Line 15: We print the output array myarray.
  • Notice from the code output that the substring "ou" can be found in the array's third element. Its index position in the element is 7.

    Free Resources