# numpy.char.find() function for string operations in Python

The numpy.core.defchararray.find() function is used to return the lowest index for the substring ‘sub’ i.e found in each component of the string in the specified range.

**Syntax**

numpy.core.defchararray.find(a, sub, start=0, end=None)

**Parameters:**

- a :- Input an array_like of string or Unicode that is to be searched.
- sub:- Input string or Unicode that is to be searched for.
- start, end:- (int, optional) These are the optional arguments that provide the range for the search.

**Return value:**

Returns a ndarray or int that contains the lowest index of the sub-string. If it does not find the required substring then the function returns -1.

### Examples: numpy.char.find() function

import numpy as np a='How are you' index = np.char.find(a, 're') print(index)

Output:

5

In the code, we have given a string ‘a’ as the input string and ‘re’ as the substring that is to be searched. The code returns the lowest index for the given substring in the string. Here we have not mentioned the values of start and end in the arguments to the function find. Thus it takes the default values for these arguments as start = 0 and end = None.

import numpy as np a='Welcome to codespeedy' f1 = np.char.find(a, 'co') f2 = np.char.find(a, 'co', start = 7, end = None) print(f1) print(f2)

Output:

3 11

In the above code, we apply the find function to the string ‘a’ to search for the substring ‘co’ twice. First when the start and end functions are not declared we get 3 as the output. In the second case, we initialize the start to 7 hence the substring ‘co’ is searched after the 7th position and hence the lowest index for the substring, ‘co’ is 11.

import numpy as np a='How are you' index = np.char.find(a, 'aa') print(index)

Output:

-1

In the above code, as the substring, ‘aa’ is not present in the string a thus the find function gives the output as -1.

import numpy as np a=['abcd','decde','cdse','adcscd','jjj'] index = np.char.find(a, 'cd') print(index)

Output:

[2 2 0 4 -1]

In the above code, we have entered an array of strings, ‘a’ and we search for the substring, ‘cd’ in the given array using the find function. The find function returns back an array of numbers that represent the lowest index in each of the strings for the substring, ‘cd’.

## Leave a Reply