What is the numpy.char.find() function in NumPy?

Overview

The char.find() function in Python is used to return the lowest index in the string of each element of a given array of strings where a substring sub is found.

Syntax

char.find(a, sub, start=0, end=None)
Syntax of the char.find() function

Parameter value

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

  • a: The input array of string.
  • sub: The substring to be searched for.
  • start, end: This is an optional parameter, where both are interpreted as in slice notation.

Return value

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

Example

Let's look at the code below:

import numpy as np
# creating an array of string
a = np.array(["I love Nunpy"])
# implementing the char.find() function
myarray = np.char.find(a, "love", start=0, end=None)
# printing the result
print(myarray)

Code Explanation

  • Line 1: We import the numpy module.
  • Line 3: We create an array of string a using the array() function.
  • Line 6: We implement the char.find() function on the array a by searching for the substring love in the element of the array starting from the leading character (index "0") to the last character. The result is assigned to a variable, myarray().
  • Line 9: We print the variable myarray.

Free Resources