Introduction
This lab covers the index() function of the char module in the Numpy library. The main purpose of this function is to perform a string search operation on a given array of strings. If we have an array of strings then this function will provide the first index of any substring to be searched, if it is present in the array elements.
VM Tips
After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.
Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.
If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.
Import Required Libraries
In the first step, we will import necessary libraries including the Numpy library.
import numpy as np
Create Input Array
In the second step, we will create an input array of strings.
ar = np.array(['bBaBaBb', 'baAbaB', 'abBABba'])
Use index() to Search for Substring
In the third step, we will use the index() function to search for a substring within the input array. We can specify the substring we want to search for. In this example, we are searching for the letter 'b' in the above array.
output = np.char.index(ar, sub ='b')
View Output
In the fourth step, we will view the output array to see the index values for the substring 'b' in the input array.
print ("The Output array:\n", output)
Handle Value Error
In the fifth step, we will try to search for a substring that does not exist in the input strings and handle the ValueError exception.
try:
output = np.char.index(ar, sub ='c')
print("The Output array:\n", output)
except ValueError as ve:
print("ValueError: substring not found")
Summary
In this lab, we have covered the index() function of the Numpy library. We used this function to perform a string search operation on a given array of strings, provided the first index of any substring to be searched, if it is present in the array elements and handle the ValueError exception in case the substring wasn't found.