What is the numpy.char.index() function in Python?

Overview

The char.index() function in Python returns the lowest index in the array of strings where a substring sub is found.

Syntax

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

Parameter value

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

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

Return value

The char.index() function returns an output array of integers. It returns ValueError if sub is not found.

Example

import numpy as np
# creating an array of string
a = np.array(["I love Nunpy"])
# implementing the char.find() function
myarray = np.char.index(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.index() function on a by searching for the substring love in the element of the array. We start from the leading character (index "0") to the last character. The result is assigned to a variable, myarray().
  • Line 9: We print the myarray variable.
Notice that the output is [2]. This means the character "love" can be found in index 2 because the leading character "l" can be found in index 1 of the element's string.

Free Resources