Return the lowest index in the string where substring is found using Python index()

PythonNumpyServer Side ProgrammingProgramming

Return the lowest index in the string where substring sub is found using the numpy.char.index() method in Python Numpy. The method returns the output array of ints. Raises ValueError if sub is not found. The first parameter is the input array. The second parameter is the substring to be searched.

Steps

At first, import the required library −

import numpy as np

Create a One-Dimensional array of strings −

arr = np.array(['KATIE', 'KATE'])

Displaying our array −

print("Array...\n",arr)

Get the datatype −

print("\nArray datatype...\n",arr.dtype)

Get the dimensions of the Array −

print("\nArray Dimensions...\n",arr.ndim)

Get the shape of the Array −

print("\nOur Array Shape...\n",arr.shape)

Get the number of elements of the Array −

print("\nNumber of elements in the Array...\n",arr.size)

Return the lowest index in the string where substring sub is found using the numpy.char.index() method −

print("\nResult (index() method)...\n",np.char.index(arr, 'AT'))

Example

import numpy as np

# Create a One-Dimensional array of strings
arr = np.array(['KATIE', 'KATE'])

# Displaying our array
print("Array...\n",arr)

# Get the datatype
print("\nArray datatype...\n",arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)

# Get the number of elements of the Array
print("\nNumber of elements in the Array...\n",arr.size)

# Return the lowest index in the string where substring sub is found using the numpy.char.index() method in Python Numpy
print("\nResult (index() method)...\n",np.char.index(arr, 'AT'))

Output

Array...
['KATIE' 'KATE']

Array datatype...
<U5

Array Dimensions...
1

Our Array Shape...
(2,)

Number of elements in the Array...
2

Result (index() method)...
[1 1]
raja
Updated on 25-Feb-2022 06:40:31

Advertisements